map和set两种容器的底层结构都是红黑树,所以容器中不会出现相同的元素,因此count()的结果只能为0和1,可以以此来判断键值元素是否存在,当然也可以使用find()方法判断键值是否存在。

find()方法返回值是一个迭代器,成功返回迭代器指向要查找的元素,失败返回的迭代器指向end。count()方法返回值是一个整数,1表示有这个元素,0表示没有这个元素。

std::map::find():

Return value: Iterator to an element with key equivalent to key. If no such element is found, past-the-end (see end()) iterator is returned.

std::map::count():

Return value: Number of elements with key that compares equivalent to key or x, that is either 1 or 0.

#include <string>
#include <iostream>
#include <map>
 
int main()
{
    std::map<std::string,int> my_map;
    my_map["x"] =  11;
    my_map["y"] = 23;
 
    auto it = my_map.find("x");
    if (it != my_map.end()) std::cout << "x: " << it->second << "\n";
 
    it = my_map.find("z");
    if (it != my_map.end()) std::cout << "z1: " << it->second << "\n";
 
    // Accessing a non-existing element creates it
    if (my_map["z"] == 42) std::cout << "Oha!\n";
 
    it = my_map.find("z");
    if (it != my_map.end()) std::cout << "z2: " << it->second << "\n";
}
Output:
x: 11
z2: 0



Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐