博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ STL常用算法-62-查找算法_binary_search/count/count_if
阅读量:4301 次
发布时间:2019-05-27

本文共 2304 字,大约阅读时间需要 7 分钟。

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

 

1.binary_search 二分查找

功能描述:

查找指定元素是否存在,返回布尔值类型

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

注意事项:

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

 

#include 
#include
#include
#include
using namespace std;void test01(){ vector
v; for(int i = 0; i < 10; i++) { v.push_back(i); } // binary_search 二分查找 bool res1 = binary_search(v.begin(), v.end(), 6); cout << res1 << endl; bool res2 = binary_search(v.begin(), v.end(), 9); cout << res2 << endl; bool res3 = binary_search(v.begin(), v.end(), 11); cout << res3 << endl;}int main(){ test01(); system("pause"); return 0;}

测试结果

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

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

 

2.count  查找统计

统计元素个数

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

#include 
#include
#include
#include
using namespace std;void test01(){ vector
v; v.push_back(10); v.push_back(20); v.push_back(10); v.push_back(20); v.push_back(50); // count 统计元素出现次数 int res1 = count(v.begin(), v.end(), 10); cout << res1 << endl; int res2 = count(v.begin(), v.end(), 20); cout << res2 << endl; int res3 = count(v.begin(), v.end(), 60); cout << res3 << endl;}int main(){ test01(); system("pause"); return 0;}

代码运行结果:

 

3.count_if带条件查找统计

按条件统计出现次数

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

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

#include 
#include
#include
#include
using namespace std;class MyCount{public: bool operator()(int val) { return val > 20; }};void test01(){ vector
v; v.push_back(10); v.push_back(30); v.push_back(10); v.push_back(20); v.push_back(50); // count_if 按条件查找统计元素出现次数 int res1 = count_if(v.begin(), v.end(), MyCount()); cout << res1 << endl;}int main(){ test01(); system("pause"); return 0;}

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

代码运行结果

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

 

转载地址:http://lexws.baihongyu.com/

你可能感兴趣的文章
五步git操作搞定Github中fork的项目与原作者同步
查看>>
git 删除远程分支
查看>>
删远端分支报错remote refs do not exist或git: refusing to delete the current branch解决方法
查看>>
python multiprocessing遇到Can’t pickle instancemethod问题
查看>>
APP真机测试及发布
查看>>
iOS学习之 plist文件的读写
查看>>
通知机制 (Notifications)
查看>>
10 Things You Need To Know About Cocoa Auto Layout
查看>>
C指针声明解读之左右法则
查看>>
一个异步网络请求的坑:关于NSURLConnection和NSRunLoopCommonModes
查看>>
iOS 如何放大按钮点击热区
查看>>
ios设备唯一标识获取策略
查看>>
获取推送通知的DeviceToken
查看>>
Could not find a storyboard named 'Main' in bundle NSBundle
查看>>
CocoaPods安装和使用教程
查看>>
Beginning Auto Layout Tutorial
查看>>
block使用小结、在arc中使用block、如何防止循环引用
查看>>
iPhone开发学习笔记002——Xib设计UITableViewCell然后动态加载
查看>>
iOS开发中遇到的问题整理 (一)
查看>>
Swift code into Object-C 出现 ***-swift have not found this file 的问题
查看>>