How can I insert elements into a multimap?
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));
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.
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