C++ 标准库 - <map>

C++ std::map::count 统计等于给定键的元素个数。键唯一,因此结果只能是 0 或 1,常用来判断是否包含。

原型

size_type count(const key_type& k) const;

参数

  • k:键。

返回值

0 或 1。

示例

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

int main() {
    std::map<std::string, int> m{{"Ada", 95}};
    std::cout << m.count("Ada") << " " << m.count("x") << "\n";
    return 0;
}

输出:

1 0

注意事项

只要判断存在,find() != end() 与 count() 均可;需要取值时用 find 以免查找两次。

下一页介绍erase:按键删除。