是否有更优雅的方式有条件地插入到std :: maps的std :: maps中?

时间:2011-04-07 16:59:58

标签: c++ stl map nested

我有嵌套容器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));
        }
    }
}

两个问题:

  • 是否有更优雅(更高效?)的方式来写这个?
  • 如何使上述代码更具抽象性,以便可以使用std::map<int, std::map<U,T>U任意类型填充类型为T的容器?我试图提出一个模板功能,但根本无法使用它。

感谢您的帮助!

4 个答案:

答案 0 :(得分:4)

container[i][j] = get_some_random_obj(i,j);

如果元素不存在,则插入地图operator[]

答案 1 :(得分:1)

如果您使用operator[]来访问元素,如果还不存在,则会创建一个空元素(这可行,因为std::map::value_type必须是默认构造的):

std::map<int, std::map<int, obj> > foo;
foo[i][j] = some_object;

请注意,如果foo[i][j]已经存在,则会被新值替换。

答案 2 :(得分:0)

我不确定这里,但我认为std :: multimap可能就是你所需要的。它将为每个键处理多个对象。

答案 3 :(得分:0)

std :: map有一个insert()函数,它返回一个包含boolean和迭代器的std ::对。

如果布尔值为true,则插入成功,如果布尔值为false,则键已经存在且迭代器对应于键,因此您可以更新值。

相关问题