Shuhao Zhang tony
Shuhao Zhang tony

Reputation: 63

parameter mismatch error in map insert

I'm Javaer for many years and a newbie in C++. Recently I need to work on a C++ project, but experience some unpleasant issues when using C++, one of them is the std:map.

I'm trying to insert a key-value pair into a map function.

map[key]=value or map.emplace(key,value) works fine, but map.insert gives me [compilation error](error), which I'm totally lost. Can someone helps?

class mystructure{
private:
    int value;
public:
    mystructure(int v){
        value=v;
    }
    void print(){
        std::cout<<value<<std::endl;
    }
    std::string get_Value(){
        return std::to_string(value);
    }
};

int main(void) {

    std::map<std::string, mystructure> mymap;
    std::vector<mystructure> v = std::vector<mystructure>();
    v.push_back(*(new mystructure(17)));
    v.push_back(*(new mystructure(12)));
    v.push_back(*(new mystructure(23)));
    for (int i=0;i<v.size();i++) {
        mystructure temp=v.at(i);
        mymap.insert(temp.get_Value(),temp);//compilation error
    }
    return 0;
}

Upvotes: 1

Views: 698

Answers (1)

songyuanyao
songyuanyao

Reputation: 172934

Because std::map::insert accepts std::map::value_type (i.e. std::pair<const Key, T>) as its parameter.

You could use:

mymap.insert(std::pair<const std::string, mystructure>(temp.get_Value(), temp));

or

mymap.insert(std::make_pair(temp.get_Value(), temp));

or

mymap.insert({temp.get_Value(), temp});

LIVE

Upvotes: 3

Related Questions