如何检查 std::map 是否包含键而不执行插入?

发布于 2024-09-26 18:11:42 字数 139 浏览 0 评论 0原文

我发现检查重复项的唯一方法是插入并检查 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

向日葵 2024-10-03 18:11:42

使用 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.

意中人 2024-10-03 18:11:42

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
}

Potatoswatter's answer is all right, but I prefer to use find or lower_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<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
}
折戟 2024-10-03 18:11:42

您的愿望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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文