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