Victor Brunell
Victor Brunell

Reputation: 6418

Inserting elements into map with set value and printing the set

I'd like to build a map with an integer key and a set value. I'd like to know what the syntax for doing that should be. Also, once I have the map filled with some key and value pairs, how should the set value be printed out?

map<int, set<int> > mymap;
map[node]= // Code to insert elements into set???
 for( map<int, set<int> >::iterator ii=mymap.begin(); ii!=mymap.end(); ++ii)
{ //Code to print map??? }

Also, is there some way to add elements to a set for a key that's already been created? Any help would be much appreciated!

Upvotes: 0

Views: 2349

Answers (1)

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 8066

To insert in the set you can use the method insert. If the map key doesn't exist (node), it will be created.

See the example:

node = 1; // a map key
map<int, set<int> > mymap;
mymap[node].insert(99); //insert 99 in the set corresponding to the map key 1

for( map<int, set<int> >::iterator ii=mymap.begin(); ii!=mymap.end(); ++ii)
{ 
    cout<< "Key: "<< ii->first << " value: ";
    for (set<int>::iterator it=ii->second.begin(); it!=ii->second.end(); ++it)
    {
        cout << *it << " ";
    }
    cout << Lendl;
}

Upvotes: 2

Related Questions