功能描述:
- 对map容器进行查找数据以及统计数据
函数原型:
- find(key); //查找key是否存在,若存在,返回键值的元素的迭代器;若不存在,返回set.end();
- count(key); //统计key的元素个数
代码演示:
#include<iostream>using namespace std;#include<map>//map容器查找和统计void printMap(map<int, int>& m) {for (map<int, int>::iterator it = m.begin(); it != m.end(); it++) {cout << "key= " << (*it).first << " value= " << it->second << endl;}cout << endl;}void test01() {//创建map容器map<int, int>m;m.insert(pair<int, int>(1, 10));m.insert(pair<int, int>(2, 20));m.insert(pair<int, int>(3, 30));m.insert(pair<int, int>(3, 40));//查找map<int, int>::iterator pos = m.find(3);if (pos != m.end()) {cout << "查到了元素: key = " << (*pos).first << " value = " << pos->second << endl;}else {cout << "未找到元素" << endl;}//统计//map不允许插入重复key的元素,因此,count统计结果非0即1//multimap的count可能大于1int num = m.count(3);cout << "num = " << num << endl;}int main() {test01();return 0;}
运行结果:
