如何在不进行插入的情况下检查 std::map 是否包含键?

2022-01-07 00:00:00 c++ map stl

我发现检查重复项的唯一方法是插入并检查 std::pair.second 是否为 false,但问题是这仍然会插入如果密钥未使用,而我想要的是 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.

推荐答案

Use my_map.count( key );它只能返回0或1,本质上就是你想要的布尔结果.

Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want.

或者 my_map.find( key ) != my_map.end() 也可以.

相关文章