I need advice how to insert data into map with string
and set<string>
. I tried something like this, but it doesnt work:
#include <map>
#include <utility>
int main()
{
std::map<string, set<string> > mymap;
std::map<string, set<string> >::iterator it = mymap.begin();
mymap.insert ( std::pair<string, set<string> > ("car" , "orange") );
return (0);
}
Could someone help me? Thank you in advance.
I don't know why it seems so popular these days to avoid operator[]
for maps, it's so much more elegant than insert
. Unless of course, the slight differences (such as the need for a default constructor) cause it to not work for you, or you've determined that it is causing a performance problem. For your purposes, as you've described them, it should work fine.
mymap["car"].insert("orange");
This will construct the set if it doesn't already exist, and it will insert an element into it. In comments, you've expressed a desire to add further elements to the set, and you can use the exact same syntax.
mymap["car"].insert("blue");
If you want to ensure you have a fresh, empty set before inserting, you can always call clear()
on it.
auto & car_set = mymap["car"];
car_set.clear();
car_set.insert("orange");
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