简体   繁体   中英

How to iterate over a map of set (std::map<string,std::set< string> >) in C++?

For a particular key I want to insert and print elements of the set corresponding to that key. For, eg if I have A - Orange, apple B - Red, blue

How do I print this? So far I have written this:`

std::map<string,std::set<string> > mp;
std::map<string,std::set<string> >::const_iterator row;
std::set<string>:: const_iterator col;

mp["A"].insert("pawan");
mp["A"].insert("patil");

for (row = mp.begin(); row!= mp.end(); row++)
    for (col = row->begin(); col!=row.end(); col++)
return 0;`

I don't know how to begin. Please help!`

for(auto const& pair : mp) {
    cout << pair.first << ": ";
    for(auto const& elem : pair.second) {
        cout << elem << ", ";
    }
    cout << "\n";
}

live example

Or, if you want to use std algorithms more:

std::for_each(mp.cbegin(), mp.cend(), [](auto const& pair){
    cout << pair.first << ": ";
    std::copy(pair.second.cbegin(), pair.second.cend(), std::ostream_iterator<std::string>(std::cout, ", "));
    cout << "\n";
});

live example

The question wants to insert an element, and then print the set for that key only.

The first step is to find the set:

auto &s=mp["A"];

Now, insert values into this set:

s.insert("pawan");
s.insert("patil");

And now, iterate over the set, printing the values in the set:

for (const auto &v:s)
    std::cout << v << std::endl;
for(auto it=mp.begin();it!=mp.end();++it)  //Loop to iterate over map elements
 {
    cout<<it->first<<"=";    
    for(auto it1=it->second.begin(); it1 !=it->second.end(); it1++)
        cout<<*it1<<" ";
    cout<<"\n";   
}

The outer for loop iterates over all the elements of map and Inner for loop prints the value corresponding to set associated with the key in the map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM