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));
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));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With