功能描述:

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

    函数原型:

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

    代码演示:

    1. #include<iostream>
    2. #include<set>
    3. using namespace std;
    4. //set容器的查找和统计
    5. //查找
    6. void test01() {
    7. set<int>s1;//默认构造
    8. //插入数据只有insert方式
    9. s1.insert(40);
    10. s1.insert(10);
    11. s1.insert(30);
    12. s1.insert(20);
    13. /*s1.end()指向的是s1中最后一个元素的下一个位置*/
    14. set<int>::iterator it = s1.find(30);
    15. if (it != s1.end()) {
    16. cout << "找到元素:" << *it << endl;
    17. }
    18. else {
    19. cout << "未找到元素!" << endl;
    20. }
    21. }
    22. //统计
    23. void test02() {
    24. set<int>s1;//默认构造
    25. //插入数据只有insert方式
    26. s1.insert(40);
    27. s1.insert(10);
    28. s1.insert(30);
    29. s1.insert(20);
    30. //统计30的个数
    31. //对于set而言,统计结果要么是0,要么是1;
    32. int n = s1.count(30);
    33. cout << "30的个数为:" << n<<endl;
    34. }
    35. int main() {
    36. test01();
    37. cout << "--------------------" << endl;
    38. test02();
    39. return 0;
    40. }

    运行结果:
    image.png