Напиши код на C++: Реализация класса «multimap». Самостоятельно реализовать основные…
- User
Напиши код на C++: Реализация класса «multimap». Самостоятельно реализовать основные методы данного класса, не используя стандартный класс. В реализации должны присутствовать такие методы как: find(), count() и оператор индексирования «[]».
- Assistant
template<typename K, typename V> class MultiMap { private: struct Node { K key; V value; Node* next; Node(K k, V v) : key(k), value(v), next(nullptr) {} }; Node* head; int size; public: MultiMap(); ~MultiMap(); void insert(K key, V value); int count(K key); Node* find(K key); V& operator[](K key); };
template<typename K, typename V> MultiMap<K, V>::MultiMap() : head(nullptr), size(0) {}
template<typename K, typename V> MultiMap<K, V>::~MultiMap() { Node* cur = head; while (cur != nullptr) { Node* temp = cur; cur = cur->next; delete temp; } }
template<typename K, typename V> void MultiMap<K, V>::insert(K key, V value) { Node* temp = new Node(key, value); if (head == nullptr) { head = temp; } else { Node* cur = head; while (cur->next != nullptr) { cur = cur->next; } cur->next = temp; } size++; }
- User
Напиши к коду выше демонстративный код в функции main()
- Assistant
#include #include "multimap.h"
int main() { MultiMap<int, std::string> map;
map.insert(1, "One"); map.insert(2, "Two"); map.insert(3, "Three"); map.insert(1, "Uno"); std::cout << "Size: " << map.size << std::endl; std::cout << "Count(1): " << map.count(1) << std::endl; std::cout << "Count(2): " << map.count(2) << std::endl; std::cout << "Count(4): " << map.count(4) << std::endl; MultiMap<int, std::string>::Node* cur = map.find(1); while (cur != nullptr) { std::cout << cur->key << ": " << cur->value << std::endl; cur = cur->next; } map[4] = "Four"; map[1] = "One"; std::cout << "Count(1): " << map.count(1) << std::endl; std::cout << "Count(4): " << map.count(4) << std::endl; std::cout << "map[1]: " << map[1] << std::endl; std::cout << "map[2]: " << map[2] << std::endl; std::cout << "map[4]: " << map[4] << std::endl; return 0;}
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.