C++ STL 中的 multimap::count()
在本文中,我們將討論 C++ STL 中 multimap::count() 函式的工作原理、語法和示例。
什麼是 C++ STL 中的多重對映?
多重對映是有序關聯容器,類似於對映容器。它也有助於以特定順序儲存由鍵值和對映值組合形成的元素。在多重對映容器中,可以有多個元素與同一個鍵相關聯。資料在內部總是藉助其關聯鍵進行排序。
什麼是 multimap::count()?
Multimap::count() 函式是 C++ STL 中的一個內建函式,定義在 <map> 標頭檔案中。count() 用於統計在與該函式關聯的多重對映中具有特定鍵的元素個數。
如果多重對映容器中沒有該鍵,此函式將返回零。
語法
multimap_name.count(key_type& key);
引數
該函式接受以下引數:
鍵 - 這是我們想要搜尋並統計與此鍵關聯的元素個數的鍵。
返回值
該函式返回一個整數,即具有相同鍵的元素個數。
輸入
std::multimap<char, int> odd, eve; odd.insert(make_pair(‘a’, 1)); odd.insert(make_pair(‘a, 3)); odd.insert(make_pair(‘c’, 5)); odd.count(‘a’);
輸出
2
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
//create the container
multimap<int, int> mul;
//insert using emplace
mul.emplace_hint(mul.begin(), 1, 10);
mul.emplace_hint(mul.begin(), 2, 20);
mul.emplace_hint(mul.begin(), 2, 30);
mul.emplace_hint(mul.begin(), 1, 40);
mul.emplace_hint(mul.begin(), 1, 50);
mul.emplace_hint(mul.begin(), 5, 60);
cout << "\nElements in multimap is : \n";
cout <<"KEY\tELEMENT\n";
for (auto i = mul.begin(); i!= mul.end(); i++){
cout << i->first << "\t" << i->second << endl;
}
cout<<"Key 1 appears " << mul.count(1) <<" times in the multimap\n";
cout<<"Key 2 appears " << mul.count(2) <<" times in the multimap\n";
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出:
Elements in multimap is : KEY ELEMENT 1 50 1 40 1 10 2 30 2 20 5 60 Key 1 appears 3 times in the multimap Key 2 appears 2 times in the multimap
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP