Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert data into map<string, set<string> > C++?

Tags:

c++

string

map

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.

like image 405
user3421673 Avatar asked Nov 30 '22 00:11

user3421673


1 Answers

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");
like image 170
Benjamin Lindley Avatar answered Dec 19 '22 02:12

Benjamin Lindley