C++ 有没有一种更优雅的方法可以有条件地插入std::map的std::map?
我有嵌套的容器C++ 有没有一种更优雅的方法可以有条件地插入std::map的std::map?,c++,stl,map,nested,C++,Stl,Map,Nested,我有嵌套的容器std::map,希望正确地填充它们,或者插入新的子映射,或者在存在整数键的情况下追加到子映射。因此,我提出了如下示例: 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
std::map
,希望正确地填充它们,或者插入新的子映射,或者在存在整数键的情况下追加到子映射。因此,我提出了如下示例:
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));
}
}
}
intn=。。。;
int m=。。。;
obj获取一些随机对象(inti,intj);//返回某个对象
std::映射容器;//预填充容器
//插入一些新的obj。如果在容器中找不到键i,则创建新的子映射,
//以其他方式附加到现有子映射
对于(int i=0;i第二个.插入(新对);
}否则{
std::map newmap;
newmap.insert(newpair);
container.insert(std::make_pair(i,newmap));
}
}
}
两个问题:
- 有没有一种更优雅(更有效?)的写作方法
- 如何使上面的代码更抽象,从而可以用类型
std::map填充容器我不确定,但我认为std::multimap可能是您所需要的。它将处理每个键的多个对象。这里我不确定,但我认为std::multimap可能是您所需要的。它将处理每个关键点的多个对象
如果元素不存在,映射的container[i][j] = get_some_random_obj(i,j);
将插入操作符[]
如果元素不存在,映射的
将插入。如果使用运算符[]
访问元素,如果还不存在,将创建一个空的元素(这是因为运算符[]
必须是默认可构造的):std::map::value\u type
std::map foo; foo[i][j]=某个对象;
请注意,如果
已经存在,它将被新值替换。如果使用foo[i][j]
访问元素,如果还不存在,将创建一个空的元素(这是因为操作符[]
必须是默认可构造的):std::map::value\u type
请注意,如果std::map foo; foo[i][j]=某个对象;
已经存在,它将被新值替换。std::map有一个insert()函数,它返回一个包含布尔值和迭代器的std::pair 如果布尔值为true,则插入成功;如果布尔值为false,则键已存在,迭代器与键对应,因此您可以更新值。std::map有一个insert()函数,该函数返回包含布尔值和迭代器的std::pairfoo[i][j]
如果布尔值为true,则插入成功;如果布尔值为false,则键已经存在,迭代器与键对应,因此您可以更新值。非常简单。。。谢谢你,非常简单。。。非常感谢。std::map<int, std::map<int, obj> > foo; foo[i][j] = some_object;