如何检查 std::map 是否包含键而不执行插入?
我发现检查重复项的唯一方法是插入并检查 std::pair.second
是否为 false
,但问题是,如果key 未使用,而我想要的是一个 map.contains(key);
函数。
The only way I have found to check for duplicates is by inserting and checking the std::pair.second
for 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 my_map.count( key ) ;它只能返回 0 或 1,这本质上是您想要的布尔结果。
或者
my_map.find( key ) != my_map.end()
也可以。Use
my_map.count( key )
; it can only return 0 or 1, which is essentially the Boolean result you want.Alternately
my_map.find( key ) != my_map.end()
works too.Potatoswatter 的答案是好的,但我更喜欢使用
find
或lower_bound
代替。lower_bound
特别有用,因为如果您希望插入具有相同键的内容,则返回的迭代器随后可用于提示插入。Potatoswatter's answer is all right, but I prefer to use
find
orlower_bound
instead.lower_bound
is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.您的愿望
map.contains(key)
已安排在标准草案C++2a 并在 C++20 中实现。 2017 年,它由 gcc 9.2 实现。它也在 clang 中。Your desideratum,
map.contains(key)
, was scheduled for the draft standard C++2a and implemented in C++20. In 2017 it was implemented by gcc 9.2. It's also in clang.