c++ - 在循环范围内填充 C++ 映射内容

标签 c++ map scope set

我尝试在循环范围内填充 C++ 映射的内容。

#include <set>
#include <map>

map<int, set<int> > maps;

for (int i=0; i<10; i++) {
   set<int> seti;    // content: a set of integers
   seti.insert(i);
   seti.insert(...);
   maps.insert ( pair<int,set<int> >(i,seti) );
}

问题是: maps.insert 是否复制配对内容? 如果在每个循环作用域后 pair 实例无效,那么这样的代码应该失败。

我应该如何正确生成 map 内容(使用指针和新实例?)以及如何正确清理 map ?

感谢您对最佳实践的任何建议。

---更新---

map<int, set<int> >::iterator it;
int k      = (*it).first;     
set<int> v = (*it).second;       

现在'v'也是从存储在 map 中的真实实例中复制的吗?
如果是,那么我就没有办法“直接”更新 map 内容。

最佳答案

您不必显式创建集合对象,因为它会在您使用 [] 运算符访问它时在 map 中创建。因此,你可以简单地写

#include <set>
#include <map>

map<int, set<int> > maps;

for (int i=0; i<10; i++) {
   maps[i].insert(i);
}

关于c++ - 在循环范围内填充 C++ 映射内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3970395/

相关文章:

c++ - Linux 多线程应用程序中的中断生成 SIGSEGV

Java从某个索引迭代 map

javascript - 全局变量保留旧值

Python 名称阴影混淆

C++ 新手 : proper way to avoid redundant object copies when initializing?

c++ - Visual Studio 2008 IDE - 静态链接 C Dll 库

c++ - Qt Creator 以用户身份编写代码,但以 root 身份运行和调试

c++ - 错误 C2064 : term does not evaluate to a function taking 0 arguments

javascript - 我如何使用当前的网络技术生成六 Angular 形交互式 map

c++ - 如何获取采用可调用项来匹配类型的函数模板?