Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

Напиши код на C++. Самостоятельно реализовать основные методы класса multimap, не…

  1. User

    Напиши код на C++. Самостоятельно реализовать основные методы класса multimap, не используя стандартный класс. В реализации должны присутствовать такие методы как: find(), count() и оператор индексирования «[]».

  2. Assistant

    // Header file for multimap implementation // Author: AI

    #ifndef MULTIMAP_H #define MULTIMAP_H

    #include #include #include // For std::sort

    template <typename K, typename V> class Pair{ public: K key; V value;

    Pair(K k, V v){
        key = k;
        value = v;
    }
    
    bool operator <(const Pair<K, V>& other) const{ // For std::sort
        return key < other.key;
    }
    

    };

    template <typename K, typename V> class multimap{ private: std::vector<Pair<K, V>> map;

    public: void insert(K key, V value){ map.emplace_back(key, value); std::sort(map.begin(), map.end()); // Sort the vector in case a new key was added }

    std::vector<V> find(K key){
        std::vector<V> result;
        for(auto it = map.begin(); it != map.end(); ++it){
            if(it->key == key) result.push_back(it->value);
        }
        return result;
    }
    
    int count(K key){
        int counter = 0;
        for(auto it = map.begin(); it != map.end(); ++it){
            if(it->key == key) counter++;
        }
        return counter;
    }
    
    V& operator [](K key){
        for(auto it = map.begin(); it != map.end(); ++it){
            if(it->key == key) return it->value;
        }
        insert(key, V()); // If key does not exist, insert it with a default value and return it
        return map.back().value;
    }
    

    };

    #endif /* MULTIMAP_H */

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.