【C++ STL学习之七】STL算法之find和find_if
2012-04-23 20:49
459 查看
一、find()算法
如果没有找到匹配元素,则返回end。
复杂度:线性复杂度。最多比较次数是:元素的总个数。
程序实例:
下面的程序在int类型的vector中搜寻元素5和12,如果搜索到,就返回其位置if欧泽输出提示信息。
main.cpp(头文件algostuff.h和上一篇博客中的相同):
![](http://my.csdn.net/uploads/201204/23/1335185138_1981.jpg)
二、find_if()算法
如果没找到,返回end。
程序实例:
下面程序找出第一个能够被3整除的元素,如果找到返回其位置。
main.cpp:
template<class InputIterator, class T> InputIterator find ( InputIterator first, InputIterator last, const T& value ) { for ( ;first!=last; first++) if ( *first==value ) break; return first; }返回区间[first,end)中第一个值等于value的元素的位置。
如果没有找到匹配元素,则返回end。
复杂度:线性复杂度。最多比较次数是:元素的总个数。
程序实例:
下面的程序在int类型的vector中搜寻元素5和12,如果搜索到,就返回其位置if欧泽输出提示信息。
main.cpp(头文件algostuff.h和上一篇博客中的相同):
#include "algostuff.h" using namespace std; int main() { vector<int> intVec; INSERT_ELEMENTS(intVec,1,9); vector<int>::iterator pos; pos = find(intVec.begin(),intVec.end(),5); if(pos != intVec.end()) cout << "The value 5 exists,and its position is " << distance(intVec.begin(),pos) + 1 << endl; else cout << "The value 4 not found!" << endl; pos = find(intVec.begin(),intVec.end(),12); if(pos != intVec.end()) cout << "The value 12 exists,and its position is " << distance(intVec.begin(),pos) + 1 << endl; else cout << "The value 12 not found!" << endl; }运行结果(头文件algostuff.h和上一篇博客中的相同):
![](http://my.csdn.net/uploads/201204/23/1335185138_1981.jpg)
二、find_if()算法
template<class InputIterator, class Predicate> InputIterator find_if ( InputIterator first, InputIterator last, Predicate pred ) { for ( ; first!=last ; first++ ) if ( pred(*first) ) break; return first; }它在区间[first,end)中搜寻使一元判断式pred为true的第一个元素。
如果没找到,返回end。
程序实例:
下面程序找出第一个能够被3整除的元素,如果找到返回其位置。
main.cpp:
#include "algostuff.h" using namespace std; int main() { vector<int> intVec; INSERT_ELEMENTS(intVec,1,9); vector<int>::iterator pos; pos = find_if(intVec.begin(),intVec.end(), not1(bind2nd(modulus<int>(),3))); if(pos != intVec.end()) cout << "The value divided by 3 exists,and the first value's position is " << distance(intVec.begin(),pos) + 1 << endl; else cout << "The value divided by 3 not found!" << endl; }运行结果:
![](http://my.csdn.net/uploads/201204/23/1335185584_6613.jpg)
相关文章推荐
- 【C++ STL学习之七】STL算法之find和find_if
- STL算法find,find_if,find_if_not,sort,fill,for_each,count,adjacent_find,random_shuffle,prev_permutation
- STL 查找vector容器中的指定对象:find()与find_if()算法
- STL中泛型算法find_if()与sort()的应用举例及详解
- STL中vector查找算法find()和find_if()深入比较
- STL中泛型算法find_if()与sort()的应用举例及详解
- STL_算法_查找算法(find、find_if)
- STL_算法_查找算法(find、find_if)
- STL之vector,数组线性容器array,list容器,算法find,find_if,bind1st,仿函数
- STL中泛型算法find_if()与sort()的应用举例及详解
- Windows STL算法学习一 find与find_if
- stl 的find_if算法用来查找容器内的符合条件的元素
- 使用STL通用算法find_if()在list中搜索对象
- STL 查找vector容器中的指定对象:find()与find_if()算法
- STL 算法Find_if_not+匿名函数
- STL算法find_if和find
- STL_算法_元素计数(count、count_if)
- 关于在STL容器list中使用find_if搜索特定的节点
- STL源码剖析——STL算法之find查找算法
- 记录 C++ STL 中 一些好用的函数--持续更新 (for_each,transform,count_if,find_if)