![](/img/trans.png)
[英]How to iterate over a map of set (std::map<std::set< char>, int >) in C++?
[英]How to iterate over a map of set (std::map<string,std::set< string> >) in C++?
對於特定的鍵,我想插入和打印與該鍵對應的集合的元素。 例如,如果我有 A - 橙色,蘋果 B - 紅色,藍色
我如何打印這個? 到目前為止,我已經寫了這個:`
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;`
我不知道如何開始。 請幫忙!`
for(auto const& pair : mp) {
cout << pair.first << ": ";
for(auto const& elem : pair.second) {
cout << elem << ", ";
}
cout << "\n";
}
或者,如果您想更多地使用標准算法:
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";
});
問題想要插入一個元素,然后僅打印該鍵的集合。
第一步是找到集合:
auto &s=mp["A"];
現在,將值插入到這個集合中:
s.insert("pawan");
s.insert("patil");
現在,迭代集合,打印集合中的值:
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";
}
外部 for 循環遍歷地圖的所有元素,內部 for 循環打印與地圖中鍵關聯的集合對應的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.