地图插入中的参数不匹配错误

parameter mismatch error in map insert

我是多年的 Javaer,也是 C++ 的新手。最近我需要做一个C++项目,但是在使用C++的时候遇到了一些不愉快的问题,其中之一就是std:map.

我正在尝试将键值对插入映射函数。

map[key]=valuemap.emplace(key,value) 工作正常,但 map.insert 给我 [编译错误](),我完全迷路了。有人可以帮忙吗?

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;
}

因为std::map::insert接受std::map::value_type(即std::pair<const Key, T>)作为参数。

您可以使用:

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

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

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

LIVE