在本文中,我们将讨论C ++ STL中map::empty()函数的工作,语法和示例。
映射是关联容器,它有助于按特定顺序存储键值和映射值的组合所形成的元素。在映射容器中,数据始终在内部借助其关联的键进行排序。映射容器中的值通过其唯一键访问。
map::count()是<map>头文件下的函数。此函数对具有特定键的元素进行计数,如果包含键的元素存在,则返回1,如果容器中不存在具有键的元素,则返回0。
map_name.count(key n);
此函数接受参数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.