說我有兩個map
s。這些map
的值是相同的並且構造(不復制)是昂貴的。這些map
的鍵具有不同的類型,但可以相互轉換。我需要設置第一個map
的內容以匹配第二個的內容,但是我必須循環遍歷map
s。有沒有辦法做到這一點?作爲這方面的一個例子,我已經簡化了一些更可識別的轉換鍵,並且只使用了int
s作爲值。在示例中,我想設置foo
的內容以匹配bar
的內容。但我無法找到一種方法來做到這一點,沒有循環通過map
s。匹配地圖不重新創建
map<int, int> foo = {{1, 100}, {2, 200}, {4, 400}};
map<char, int> bar = {{'1', 200}, {'3', 300}, {'5', 500}};
for(auto i = foo.begin(); i != foo.end(); ++i) {
if(bar.end() == bar.find(static_cast<decltype(bar)::key_type>(i->first) + '0')){
foo.erase(i);
}
}
for(auto i = bar.begin(); i != bar.end(); ++i) {
const decltype(foo)::key_type key = i->first - '0';
if(foo.end() == foo.find(key) || foo[key] != i->second) {
foo[key] = i->second;
}
}
for(const auto i : foo){
cout << i.first + 10 << ": " << i.second << endl;
}
此正確地輸出:
11:200
13:300
15:500
有一種做這不需要通過兩者循環map
s?
按鍵的排序是否相同? – rici
@rici是的,他們這樣做。 –
在這種情況下,您可以通過並行和合並循環兩個貼圖來獲得相同的結果。這避免了'bar.find()'調用,但你仍然需要迭代兩個地圖。我不知道這個方法。 – rici