我有嵌套容器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));
}
}
}
兩個問題:
- 是否有一個更優雅(更有效率?)的方式來寫這個?
- 如何才能使上述代碼更加抽象,以便使用
U
和T
任意類型填充容器的類型爲std::map<int, std::map<U,T>
成爲可能?我試圖想出一個模板函數,但根本無法讓它工作。
謝謝你的幫忙!
尷尬簡單...謝謝, – bbtrb 2011-04-07 17:19:42