C ++如何在multimap中插入?

时间:2013-01-26 15:16:15

标签: c++ multimap

我想在C ++中设置一个多图:

multimap<pair<string, string>, vector<double> > mmList;

但是如何插入数据:

mmList.insert(pair<string, string>, vector<double>("a", "b", test));

3 个答案:

答案 0 :(得分:19)

您可以使用std::make_pair(a, b)构建对。通常,您可以将对插入到地图/多图中。在你的情况下,你必须构造一个由字符串对和向量组成的对:

    std::multimap<std::pair<std::string, std::string>, std::vector<double> > mmList;

    std::vector<double> vec;
    mmList.insert(std::make_pair(std::make_pair("a","b"), vec));

答案 1 :(得分:1)

以下是示例:

std::multimap<std::string,std::string> Uri_SessionId_Map;
std::string uri = "http";
std::string sessId = "1001";
std::pair<std::string,std::string> myPair(uri,sessId);
Uri_SessionId_Map.insert(myPair);

为了更好的可读性,只打破了几行。你可以理解如何配对。对必须具有与multimap相同的模板形式。

答案 2 :(得分:0)

C++11相比,自std::multimap::emplace()起,您可以使用harpun's answer摆脱一个* def temp = { foo: { bar: { a: 1 } } } # * def temp = { foo: [{ bar: { a: 1 } }] } * if (temp.foo.bar) karate.set('temp', '$.foo', [temp.foo]) * match temp == { foo: [{ bar: { a: 1 } }] }

std::make_pair()

上面的代码不仅更短,而且效率更高,因为它减少了std::pair构造函数的不必要的调用。 为了进一步提高效率,您可以使用std::multimap<std::pair<std::string, std::string>, std::vector<double>> mmList; std::vector<double> test = { 1.1, 2.2, 3.3 }; mmList.emplace(std::make_pair("a", "b"), test); 的{​​{1}}构造函数,该构造函数是针对您的用例专门引入的:

piecewise_construct

此代码不再短一些,但具有不会调用不必要的构造函数的效果。根据给定的参数直接在std::pair中创建对象。

Code on Ideone