Search code examples
c++c++11multimap

How to implement the below function getValue(m) for multimap in C++


#include<bits/stdc++.h>
using namespace std;
void getValue(multimap<int,string> &m){
    for(auto &mValue : m){
        cout<<mValue.first<<" "<<mValue.second<<endl;
    }
}
int main(){
    int n;
    cin>>n;
    multimap<int,string> m;
    
    for(int i=0;i<n;i++){
        int num;
        string str;
        cin>>num;
        getline(cin,str);
        m.insert(make_pair(num,str));
    }
    

    getValue(m);
    return 0;
}

Error : invalid initialization of reference of type ‘std::map >&’ from expression of type ‘std::multimap >’ getValue(m);


Solution

  • std::map<int, std::string> is a different type to std::multimap<int, std::string>, although they bear similarities.

    The simplest way would to write a similar function:

    void getValue(const std::multimap<int, std::string> &m){
        for(auto &mValue : m){
            std::cout<<mValue.first<<" "<<mValue.second<<std::endl;
        }
    }
    

    However there a a number of map-like containers in std and beyond, so you might want to change getValue to be a template

    template <typename Map>
    void getValue(const Map &m){
        for(auto &mValue : m){
            std::cout<<mValue.first<<" "<<mValue.second<<std::endl;
        }
    }
    

    You might want to constrain that to only accept map-like types, e.g. (with C++17's library addition of std::void_t)

    template <typename Map>
    std::void_t<typename Map::key_type, typename Map::mapped_type> getValue(const Map &m){
        for(auto &mValue : m){
            std::cout<<mValue.first<<" "<<mValue.second<<std::endl;
        }
    }