Напиши код на C++. Самостоятельно реализовать основные методы класса multimap, не…
- User
Напиши код на C++. Самостоятельно реализовать основные методы класса multimap, не используя стандартный класс. В реализации должны присутствовать такие методы как: find(), count() и оператор индексирования [].
- Assistant
#include #include
using namespace std;
template <typename K, typename V> class Node { public: K key; V value; Node<K, V>* next;
Node() {} Node(K key, V value) { this->key = key; this->value = value; next = NULL; } Node(const Node& other) { key = other.key; value = other.value; next = other.next; }};
template <typename K, typename V> class multimap { private: int size; Node<K, V>** table; int tableSize;
int hash(K key) { return (key % tableSize); }public: multimap() { size = 0; tableSize = 100; table = new Node<K, V>*[tableSize]; for (int i = 0; i < tableSize; i++) { table[i] = NULL; } }
~multimap() { Node<K, V>* current; Node<K, V>* next; for (int i = 0; i < tableSize; i++) { current = table[i]; while (current != NULL) { next = current->next; delete current; current = next; } } delete[] table; } void insert(K key, V value) { int index = hash(key); Node<K, V>* node = new Node<K, V>(key, value); if (table[index] == NULL) { table[index] = node; } else { Node<K, V>* current = table[index]; while (current->next != NULL) { current = current->next; } current->next = node; } size++; } Node<K, V>* find(K key) { int index = hash(key); Node<K, V>* current = table[index]; while (current != NULL) { if (current->key == key) { return current; } current = current->next; } return NULL; } int count(K key) { int index = hash(key); int count = 0; Node<K, V>* current = table[index]; while (current != NULL) { if (current->key == key) { count++; } current = current->next; } return count; } V& operator[](K key) { Node<K, V>* node = find(key); if (node != NULL) { return node->value; } else { V value = V(); insert(key, value); node = find(key); return node->value; } }};
int main() { multimap<int, string> myMap;
myMap.insert(1, "one"); myMap.insert(2, "two"); myMap.insert(3, "three"); myMap.insert(2, "two2"); myMap.insert(3, "three2"); myMap.insert(3, "three3"); cout << myMap.count(2) << endl; cout << myMap[3] << 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.