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