2011-04-07 42 views
0

我有嵌套容器std::map<int, std::map<T, U> >,並希望正確填充它們,要麼插入一個新的子映射,要麼附加到子映射如果整數鍵存在。所以,我想出了類似下面的例子:有沒有更優雅的方式來有條件地插入std :: maps的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)); 
     } 
    } 
} 

兩個問題:

  • 是否有一個更優雅(更有效率?)的方式來寫這個?
  • 如何才能使上述代碼更加抽象,以便使用UT任意類型填充容器的類型爲std::map<int, std::map<U,T>成爲可能?我試圖想出一個模板函數,但根本無法讓它工作。

謝謝你的幫忙!

回答

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

map's operator[]如果元素不存在,則插入。

+0

尷尬簡單...謝謝, – bbtrb 2011-04-07 17:19:42

0

我不確定在這裏,但我認爲std :: multimap可能是你需要的。它將處理每個鍵的多個對象。

1

如果使用operator[]訪問元素,空單會如果沒有還不存在創建(這工作,因爲std::map::value_type必須是默認constructible):

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

需要注意的是,如果foo[i][j]已經存在,它將被新值所取代。

0

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

如果布爾值爲true,則插入成功,如果布爾值爲false,則該鍵已經存在,並且迭代器對應於該鍵,因此您可以更新該值。

相關問題