C++算法的find()函数在参数列表中指定一个值,在参数内搜索该值,如果该元素在参数内找到,则迭代器从第一个元素开始搜索并继续到最后一个元素然后返回它,否则给出参数的最后一个元素。
template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& value);
first - 它指定参数的第一个元素。
last - 它指定参数的最后一个元素。
value - 它指定要在参数内搜索的值。
该函数将迭代器返回到等于该值的参数的第一个元素。如果找不到这样的元素,则该函数返回最后一个元素。
#include <iostream> #include <algorithm> #include <vector> int main () { int newints[] = { 50, 60, 70, 80 }; int * q; q = std::find (newints, newints+4, 60); if (q != newints+4) std::cout << "Element found in newints: " << *q << '\n'; else std::cout << "Element not found in newints\n"; std::vector<int> newvector (newints,newints+4); std::vector<int>::iterator ti; ti = find (newvector.begin(), newvector.end(), 60); if (ti != newvector.end()) std::cout << "Element found in newvector: " << *ti << '\n'; else std::cout << "Element not found in newvector\n"; return 0; }
输出:
Elements that are found in newints: 60 Elements that are found in newvector: 60
#include<iostream> #include<algorithm> #include<vector> int main() { std::vector<int> vct {50,60,70,80}; std::vector<int>::iterator ti; std::cout<<"Initial vector:"; for(int k=0; k<vct.size(); k++) std::cout<<" "<<vct[k]; std::cout<<"\n"; int sr = 60; ti = std::find(vct.begin(), vct.end(),sr); if(ti!=vct.end()) { std::cout<< "The element "<<"has been found at position:"; std::cout<<ti-vct.begin() +1<<"\n"; } else std::cout<<"Element does not exist.\n \n"; return 0; }
输出:
Intitial vector: 50 60 70 80 The element 30 has been found at position: 2
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)