功能描述:

    • 对map容器进行查找数据以及统计数据

    函数原型:

    • find(key); //查找key是否存在,若存在,返回键值的元素的迭代器;若不存在,返回set.end();
    • count(key); //统计key的元素个数

    代码演示:

    1. #include<iostream>
    2. using namespace std;
    3. #include<map>
    4. //map容器查找和统计
    5. void printMap(map<int, int>& m) {
    6. for (map<int, int>::iterator it = m.begin(); it != m.end(); it++) {
    7. cout << "key= " << (*it).first << " value= " << it->second << endl;
    8. }
    9. cout << endl;
    10. }
    11. void test01() {
    12. //创建map容器
    13. map<int, int>m;
    14. m.insert(pair<int, int>(1, 10));
    15. m.insert(pair<int, int>(2, 20));
    16. m.insert(pair<int, int>(3, 30));
    17. m.insert(pair<int, int>(3, 40));
    18. //查找
    19. map<int, int>::iterator pos = m.find(3);
    20. if (pos != m.end()) {
    21. cout << "查到了元素: key = " << (*pos).first << " value = " << pos->second << endl;
    22. }
    23. else {
    24. cout << "未找到元素" << endl;
    25. }
    26. //统计
    27. //map不允许插入重复key的元素,因此,count统计结果非0即1
    28. //multimap的count可能大于1
    29. int num = m.count(3);
    30. cout << "num = " << num << endl;
    31. }
    32. int main() {
    33. test01();
    34. return 0;
    35. }

    运行结果:
    image.png