C++ STL常用算法-62-查找算法_binary_search/count/count_if

骑猪看日落 2022-11-29 14:29 207阅读 0赞

前面一篇学习了常用查找算法的三个方法,现在接着学习剩下三个查找相关的算法。binary_search,这个二分查找,在任何语言中都是重点需要掌握的,面试经常被考察。二分查找是一种解决问题的思想,在实际工作中排查错误,定位什么节点开始出现错误的,也是通过人工二分查找或者自动化脚本二分查找去定位。count是查找出现元素的个数,count_if是带条件查找统计结果的函数。

1.binary_search 二分查找

功能描述:
查找指定元素是否存在,返回布尔值类型

函数原型:bool binary_search(iterator beg, iterator end, value);

注意事项:
查找指定的元素,查找到返回true,否则返回false
只能在有序序列中使用,也就是排好序才能使用二分查找算法

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  6. void test01()
  7. {
  8. vector<int> v;
  9. for(int i = 0; i < 10; i++)
  10. {
  11. v.push_back(i);
  12. }
  13. // binary_search 二分查找
  14. bool res1 = binary_search(v.begin(), v.end(), 6);
  15. cout << res1 << endl;
  16. bool res2 = binary_search(v.begin(), v.end(), 9);
  17. cout << res2 << endl;
  18. bool res3 = binary_search(v.begin(), v.end(), 11);
  19. cout << res3 << endl;
  20. }
  21. int main()
  22. {
  23. test01();
  24. system("pause");
  25. return 0;
  26. }

测试结果

20200822093110482.png

数字1表示true,数字0表示false

如果序列不是有序,先需要排序,例如利用sort()算法。

2.count 查找统计

统计元素个数

函数原型:int count(iterator beg, iterator end, value);

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  6. void test01()
  7. {
  8. vector<int> v;
  9. v.push_back(10);
  10. v.push_back(20);
  11. v.push_back(10);
  12. v.push_back(20);
  13. v.push_back(50);
  14. // count 统计元素出现次数
  15. int res1 = count(v.begin(), v.end(), 10);
  16. cout << res1 << endl;
  17. int res2 = count(v.begin(), v.end(), 20);
  18. cout << res2 << endl;
  19. int res3 = count(v.begin(), v.end(), 60);
  20. cout << res3 << endl;
  21. }
  22. int main()
  23. {
  24. test01();
  25. system("pause");
  26. return 0;
  27. }

代码运行结果:

20200822130825650.png

3.count_if带条件查找统计

按条件统计出现次数

这个条件可以是一个仿函数或者一个回调函数

函数原型:count_if(iterator beg, iterator end, _pred);

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  6. class MyCount
  7. {
  8. public:
  9. bool operator()(int val)
  10. {
  11. return val > 20;
  12. }
  13. };
  14. void test01()
  15. {
  16. vector<int> v;
  17. v.push_back(10);
  18. v.push_back(30);
  19. v.push_back(10);
  20. v.push_back(20);
  21. v.push_back(50);
  22. // count_if 按条件查找统计元素出现次数
  23. int res1 = count_if(v.begin(), v.end(), MyCount());
  24. cout << res1 << endl;
  25. }
  26. int main()
  27. {
  28. test01();
  29. system("pause");
  30. return 0;
  31. }

上面使用了仿函数,里面写了一个元素大于20的判断,也就是遍历过程中加上这个条件,找出元素大于20的元素出现次数

代码运行结果

20200822131516906.png

上面明显只有元素30 和50大于20,所以结果是2

发表评论

表情:
评论列表 (有 0 条评论,207人围观)

还没有评论,来说两句吧...

相关阅读