c++ - 将元素插入具有设定值的 map 并打印集合

标签 c++ dictionary insert set

我想用一个整数键和一个设定值构建一个 map 。我想知道这样做的语法应该是什么。另外,一旦我用一些键值对填充了 map ,应该如何打印出设置值?

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??? }

此外,是否有某种方法可以将元素添加到已创建的键的集合中?任何帮助将不胜感激!

最佳答案

要在集合中插入,您可以使用方法insert。如果映射键不存在(节点),将创建它。

看例子:

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;
}

关于c++ - 将元素插入具有设定值的 map 并打印集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101531/

相关文章:

Python:将函数应用于数据帧的多个子集(存储在字典中)

mysql - 使用单个查询将值插入多个表

java - 递归插入到双向链表的末尾

C++正则表达式匹配整行

c++ - 如何让线程等待条件执行操作而不使用过多的 CPU 时间?

c++ - 除了用宏,不能用 C++ 表达自己

python - 如何在 JSON 键中指定值

c++ - 在 C++ 应用程序中添加脚本

mongodb - MongoDB 中的只写集合