C++ 如何在不进行插入的情况下检查 std::map 是否包含键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3886593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if std::map contains a key without doing insert?
提问by jmasterx
The only way I have found to check for duplicates is by inserting and checking the std::pair.secondfor false, but the problem is that this still inserts something if the key is unused, whereas what I want is a map.contains(key);function.
我发现检查重复项的唯一方法是插入并检查std::pair.secondfor false,但问题是如果密钥未使用,这仍然会插入一些东西,而我想要的是一个map.contains(key);函数。
回答by Potatoswatter
Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want.
使用my_map.count( key ); 它只能返回 0 或 1,这本质上是你想要的布尔结果。
Alternately my_map.find( key ) != my_map.end()works too.
交替my_map.find( key ) != my_map.end()工作。
回答by Chris Jester-Young
Potatoswatter's answer is all right, but I prefer to use findor lower_boundinstead. lower_boundis especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.
Potatoswatter 的回答没问题,但我更喜欢用find或lower_bound代替。lower_bound尤其有用,因为返回的迭代器随后可用于提示插入,如果您希望插入具有相同键的内容。
map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) { // not found
// ...
my_map.insert(iter, make_pair(key, value)); // hinted insertion
} else {
// ... use iter->second here
}

