stdfind
template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);
效果
查找范围内第一次出现的 val [first,last)
参数
first
=>指向范围开头的迭代器 last
=>指向范围结束的迭代器 val
=>要在范围内查找的值
返回
迭代器指向范围内等于(==)到 val 的第一个元素,如果未找到 val,则迭代器指向 last。
例
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
//create a vector
vector<int> intVec {4, 6, 8, 9, 10, 30, 55,100, 45, 2, 4, 7, 9, 43, 48};
//define iterators
vector<int>::iterator itr_9;
vector<int>::iterator itr_43;
vector<int>::iterator itr_50;
//calling find
itr_9 = find(intVec.begin(), intVec.end(), 9); //occurs twice
itr_43 = find(intVec.begin(), intVec.end(), 43); //occurs once
//a value not in the vector
itr_50 = find(intVec.begin(), intVec.end(), 50); //does not occur
cout << "first occurence of: " << *itr_9 << endl;
cout << "only occurence of: " << *itr_43 << Lendl;
/*
let's prove that itr_9 is pointing to the first occurence
of 9 by looking at the element after 9, which should be 10
not 43
*/
cout << "element after first 9: " << *(itr_9 + 1) << ends;
/*
to avoid dereferencing intVec.end(), lets look at the
element right before the end
*/
cout << "last element: " << *(itr_50 - 1) << endl;
return 0;
}
输出
first occurence of: 9
only occurence of: 43
element after first 9: 10
last element: 48