【问题标题】:Is there a more elegant way to conditionally insert into a std::map of std::maps?有没有更优雅的方法有条件地插入 std::maps 的 std::map ?
【发布时间】:2011-07-31 21:13:47
【问题描述】:

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

两个问题:

  • 有没有更优雅(更高效?)的方式来写这个?
  • 如何使上述代码更加抽象,从而可以使用UT 任意类型填充std::map&lt;int, std::map&lt;U,T&gt; 类型的容器?我试图想出一个模板函数,但根本无法让它工作。

感谢您的帮助!

【问题讨论】:

    标签: c++ stl map nested


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      container[i][j] = get_some_random_obj(i,j);
      

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

      【讨论】:

      • 尴尬的简单...谢谢,
      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

        std::map 有一个 insert() 函数,它返回一个包含布尔值和迭代器的 std::pair。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-12
          • 1970-01-01
          • 2012-04-22
          相关资源
          最近更新 更多