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