C++ 中的 map count() 函数
在本文中,我们将讨论 C++ STL 中 map::empty() 函数的工作原理、语法和示例。
什么是 C++ STL 中的 Map?
Map 是关联容器,它可以方便地存储由键值对组成的元素,并按照特定顺序排列。在 map 容器中,数据内部始终借助其关联的键进行排序。map 容器中的值可以通过其唯一的键进行访问。
什么是 map::count()?
map::count() 函数位于 <map> 头文件中。此函数计算具有特定键的元素个数,如果存在具有该键的元素,则返回 1;如果容器中不存在具有该键的元素,则返回 0。
语法
map_name.count(key n);
参数
此函数接受参数 N,它指定容器中的键。
返回值
如果容器中存在该键,则此函数返回布尔值 1;如果容器中不存在该键,则返回 0。
输入 (键, 元素)
(2,70), (3,30), (4,90), (5,100)
输出
Key 5 is present. Key 6 is not present. 2,11 3,26 1,66 4,81 Key 2 is present. Key 8 is not present.
可遵循的方法
首先初始化容器。
然后插入带有其键的元素。
然后我们检查容器中是否存在所需的键。
使用上述方法,我们可以检查容器中是否存在键;还可以遵循另一种方法:
首先,我们初始化容器。
然后我们插入带有其键的元素。
然后我们从第一个元素到最后一个元素创建循环。
在这个循环中,我们检查所需的键是否存在。
上述方法通常用于按字母顺序存储的元素。在此方法中,代码在输出中打印元素是否存在。
示例
/ / C++ code to demonstrate the working of map count( ) function
#incude<iostream.h>
#include<map.h>
Using namespace std;
int main( ){
map<int, int> mp;
mp.insert({1, 40});
mp.insert({3, 20});
mp.insert({2, 30});
mp.insert({5, 10});
mp.insert({4, 50});
if (mp.count(1))
cout<< ” The Key 1 is present\n”;
else
cout<< ” The Key 1 is not present\n”;
if(mp.count(7))
cout<< “ The Key 7 is Present \n”;
else
cout<< “ The Key 7 is not Present\n”;
return 0;
}输出
如果运行上述代码,它将生成以下输出
The Key 1 is present The Key 7 is not present
示例
#include<iostream.h>
#include<map.h>
Using namespace std;
int main ( ){
map<char, int> mp;
int I;
mp[‘a’] = 2;
mp[‘c’] = 3;
mp[‘e’] = 1;
for ( i = ’a’ ; i < ’f’ ; i++){
cout<< i;
if (mp.count(i)>0)
cout<< “ is an element of mp.\n”;
else
cout<< “ is not an element of mp.\n”;
}
return 0;
}输出
如果运行上述代码,它将生成以下输出
a is an element of mp. b is not an element of mp. c is an element of mp. d is not an element of mp. e is an element of mp. f is not an element of mp.
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP