c++

c++ map.count和find比较

小樊
95
2024-08-06 05:18:07
栏目: 编程语言

在C++中,map.countmap.find都是用来搜索map中指定键的函数,但它们有一些不同之处。

  1. map.count返回指定键在map中出现的次数,即返回值为0或1。如果指定键存在,则返回1,否则返回0。

示例:

std::map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
int count = myMap.count(2);
// count的值为1,因为键2存在于map中
  1. map.find返回一个迭代器,指向map中指定键的位置。如果找到指定键,则返回指向该键的迭代器;如果未找到指定键,则返回map.end()

示例:

std::map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
auto it = myMap.find(2);
if (it != myMap.end()) {
    std::cout << "Key found, value is: " << it->second << std::endl;
} else {
    std::cout << "Key not found" << std::endl;
}

总的来说,map.count适用于只需要知道指定键是否存在以及出现的次数的情况,而map.find适用于需要获取指定键的值或者进行修改操作的情况。

0
看了该问题的人还看了