unordered_map count函数(map.count())

unordered_map count函数

unordered_map::count() 是C++中的一个内置方法,用于计算给定键在 unordered_map 中存在的元素数。由于 unordered_map 不允许存储具有重复键的元素,因此 count() 函数基本上检查 unordered_map 中是否存在带有给定键的元素。

示例

#include

#include


using namespace std;


int main() {

// 创建一个 unordered_map

unordered_map<int, string> umap;


// 插入元素

umap.insert(make_pair(1, "Welcome"));

umap.insert(make_pair(2, "to"));

umap.insert(make_pair(3, "GeeksforGeeks"));


// 使用 count() 函数检查键为 1 的元素是否存在

if (umap.count(1)) {

cout << "找到元素" << endl;

} else {

cout << "未找到元素" << endl;

}


return 0;

}

输出:

找到元素

说明

  • 语法size_type count(const Key& key) const;
  • 参数:此函数接受一个单一的参数 key,需要在已给定的 unordered_map 容器中进行检查。
  • 返回值:如果映射中存在具有给定键的值,则此函数返回1,否则返回0

注意事项

由于 unordered_map 不允许存储具有重复键的元素,因此 count() 函数返回的值只能是0或1。如果需要处理可能存在重复键的情况,可以考虑使用 multimap

原文链接:,转发请注明来源!