天天看点

从C++11到C++23(六)C++20利用contains查询map是否存在某个键

在C++20以前,如果map查询是否存在某个键,需要语法为

1.使用

map::find

:

if ( m.find(key) != m.end() ) {
  std::cout << "Found\n";
} else {
  std::cout << "Not found\n";
}
           

2.使用

count

函数,使用下面三条任意一条判断语句即可:

m.count(key) > 0
m.count(key) == 1
m.count(key) != 0
           

区别:

map

set

两种容器的底层结构都是红黑树,所以容器中不会出现相同的元素,因此

count()

的结果只能为0和1,可以以此来判断键值元素是否存在,当然也可以使用

find()

方法判断键值是否存在。

find()

方法返回值是一个迭代器,成功返回迭代器指向要查找的元素,失败返回的迭代器指向end。

count()

方法返回值是一个整数,1表示有这个元素,0表示没有这个元素。

C++20新增contains函数

但在C++20新增了

std::map::contains

可以直接查找键是否存在。

#include <iostream>
#include <string>
#include <map>

int main()
{
    std::map<int, std::string> example = {{1, "One"}, {2, "Two"}, 
                                     {3, "Three"}, {42, "Don\'t Panic!!!"}};

    if(example.contains(42)) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }
}
           

继续阅读