How can I insert elements into a multimap?

18,000

Solution 1

You can construct pairs using std::make_pair(a, b). Generally you can insert pairs into maps/multimaps. In your case you have to construct a pair consisting of the string pair and the vector:

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

Solution 2

Since C++11 you can use std::multimap::emplace() to get rid of one std::make_pair() compared to harpun's answer:

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

The code above is no only shorter, but also more efficient, because it reduces the number of unnecessary calls of std::pair constructors. To further increase efficiency, you can use the piecewise_construct constructor of std::pair, which was introduced specifically for your use case:

mmList.emplace(std::piecewise_construct,
    std::forward_as_tuple("a", "b"),
    std::forward_as_tuple(test));

This code is no longer shorter, but has the effect that no unnecessary constructors are called. The objects are created directly in the std::multimap from the given arguments.

Code on Ideone

Solution 3

Here is example:

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

Just broke up few lines for more readability. You can understand how to make pair. pair must have same templatize form as multimap.

Share:
18,000
andre de boer
Author by

andre de boer

Updated on June 12, 2022

Comments

  • andre de boer
    andre de boer almost 2 years

    I want to set up a multimap in C++ as follows:

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

    But how can I insert data into it? I tried the following code, but it doesn't compile:

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