说我有两个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