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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:58:35  来源:igfitidea点击:

How to check if std::map contains a key without doing insert?

c++stlmap

提问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 的回答没问题,但我更喜欢用findlower_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
}

回答by Camille Goudeseune

Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

您的愿望,map.contains(key),已安排在标准草案C++2a 中。2017 年由gcc 9.2实现。它也在当前的clang 中