是否有更优雅的方法来有条件地插入到std::map的std::map中
Is there a more elegant way to conditionally insert into a std::map of std::maps?
我有嵌套容器std::map<int, std::map<T, U> >
,并希望正确填充它们,要么插入一个新的子映射,要么添加到子映射,如果整数键存在。所以我想到了下面的例子:
int n = ...;
int m = ...;
obj get_some_random_obj(int i, int j); // returns some object
std::map<int, std::map<int, obj> > container; // prepopulated container
// insert some new obj's. Create a new sub map if key i is not found in container,
// append to existing sub map otherwise
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
std::map<int, std::map<int, obj> >::iterator found = container.find(i);
obj newobj = get_some_random_obj(i,j);
std::pair<int, obj> newpair(j, newobj);
if(found != container.end()) {
found->second.insert(newpair);
} else {
std::map<int, obj> newmap;
newmap.insert(newpair);
container.insert(std::make_pair(i, newmap));
}
}
}
两个问题:
- 是否有更优雅(更有效)的方式来写这个?
- 如何使上面的代码更加抽象,以便可以用
U
和T
任意类型填充std::map<int, std::map<U,T>
类型的容器?我试着想出一个模板函数,但根本无法让它工作。
谢谢你的帮助!
container[i][j] = get_some_random_obj(i,j);
map的operator[]
插入如果元素不存在
如果您使用operator[]
访问元素,如果还不存在,则将创建一个空元素(这是因为std::map::value_type
必须是默认可构造的):
std::map<int, std::map<int, obj> > foo;
foo[i][j] = some_object;
注意,如果foo[i][j]
已经存在,它将被替换为新的值
我不确定这里,但我认为std::multimap可能是你需要的。
std::map有一个insert()函数,该函数返回一个包含布尔值和迭代器的std::pair。
如果布尔值为真,则插入成功,如果布尔值为假,则该键已经存在,并且迭代器对应于该键,因此可以更新该值。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map