Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert elements into a multimap?

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));
like image 229
andre de boer Avatar asked Jan 26 '13 15:01

andre de boer


2 Answers

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));
like image 77
harpun Avatar answered Oct 08 '22 16:10

harpun


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

like image 21
honk Avatar answered Oct 08 '22 16:10

honk