template <class InIt, class T>
InIt find(InIt first, InIt last, const T& val);
[first, last) 这个区间是一个左闭右开的区间,即 last 指向的元素其实不在此区间内。find 模板使用
==运算符判断元素是否相等。因此,如果 [first, last) 区间中存放的是对象,则==运算符应该被适当重载,使得两个对象可以用==运算符比较。
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int a[10] = {10,20,30,40};
vector<int> v;
v.push_back(1); v.push_back(2);
v.push_back(3); v.push_back(4); //此后v里放着4个元素:1,2,3,4
vector<int>::iterator p;
p = find(v.begin(),v.end(),3); //在v中查找3
if(p != v.end()) //若找不到,find返回 v.end()
cout << "1) " << * p << endl; //找到了
p = find(v.begin(),v.end(),9);
if(p == v.end())
cout << "not found " << endl; //没找到
p = find(v.begin()+1,v.end()-1,4); //在,3 这两个元素中查找4
cout << "2) " << * p << endl;
int * pp = find(a,a+4,20);
if(pp == a + 4)
cout << "not found" << endl;
else
cout << "3) " <<* pp << endl;
}
程序的输出结果是:a+4的类型也是 int*,因此也能做迭代器。本次调用 find,查找区间是 [a, a+4),即数组 a 的前 4 个元素。如果查找失败,find 就会返回 a+4。
template<class_RandIt>
void sort(_RandIt first, _RandIt last);
int a[4] = {3, 4, 2, 1};
sort(a, a+4);
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有