JustAnotherDoomer
JustAnotherDoomer

Reputation: 105

Setting value to a set inside a map, C++

Suppose I have a following container

 map<string, set<int>> myMap;

I want to store numbers related to the strings, as in {Cat, <1, 3 ,5>}} etc.

How does one access to the std::set inside a std::map or set/store values into it?

It seems that the simple myMap.insert( {string, number} ) doesn't cut it here.

Upvotes: 1

Views: 1207

Answers (2)

Pat. ANDRIA
Pat. ANDRIA

Reputation: 2412

You may find a proposition below, using map::iterator and std::pair:

#include <map>
#include <set>
#include <iostream>


int main()
{

    // initialize container
    std::map< std::string, std::set<int> > mp;
    std::map< std::string, std::set<int>>::iterator it = mp.begin();
    // insert elements 
    mp.insert(it, std::pair<std::string, std::set<int>>( "test", {30,3,5,6}));
    mp.insert(it, std::pair<std::string, std::set<int>>( "Value", {1,40,10}));
    mp.insert(it, std::pair<std::string, std::set<int>>( std::string("who"), {30,60}));

    //modify a set with a given key - say Value
    mp["Value"]={5,45,15};

    // display all elements
    for(auto const& mypair : mp)
    {
        std::cout << mypair.first << ": ";
        for(auto const& elem : mypair.second)
        {
            std::cout << elem << " ";
        }
        std::cout << "\n";
    }
    return 0;
}

The ouput of the code would give :

Value: 5 15 45
test: 3 5 6 30
who: 30 60

Upvotes: 0

Nicolas Degen
Nicolas Degen

Reputation: 1846

Just use map[key].insert(value);

See example:

#include <iostream>
#include <map>
#include <set>

 
int main() {
    std::map<std::string, std::set<int>> m { {"Foo", {10, 1}} };
 
    m["Foo"].insert(25);  // update an existing set
    m["Bar"] = { 30, 22 };  // insert a new set
    
    for(auto a : m["Foo"]) {
      std::cout << a << std::endl;
    }
}

Upvotes: 2

Related Questions