【问题标题】:Inserting elements into map with set value and printing the set使用设定值将元素插入地图并打印集合
【发布时间】:2015-01-23 01:13:36
【问题描述】:

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

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

另外,有没有办法为已经创建的键添加元素到集合中?任何帮助将不胜感激!

【问题讨论】:

  • 见这里std::map和这里std::set
  • 谢谢。我查看了这些,但没有任何我正在寻找的语法示例。

标签: c++ dictionary insert set


【解决方案1】:

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

看例子:

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

【讨论】:

  • 有没有办法在一次插入中将多个整数添加到集合中?类似于:mymap[node].insert(99, 100, 101);
  • @Caulibrot std::set::operator=() 第三种形式。
  • @Caulibrot 在that page dude 的示例部分。
  • std::set nums1 {3, 1, 4, 6, 5, 9};
猜你喜欢
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
相关资源
最近更新 更多