find()
参考官方网址:http://www.cplusplus.com/reference/algorithm/find/?kw=find
格式:
template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);
解释:first、last分别是搜索的起始地址,在这个空间中寻找与val相等的对象,如果找到就返回这个相等对象的地址,如果没有就返回last。如果存在多个相等的对象,只返回第一个的地址。有时候我们会想知道查找到的结果位于数组的第几个,这时候我们可以将返回来的地址减去数组的首地址。
例子:
// find example
#include <iostream> // std::cout
#include <algorithm> // std::find
#include <vector> // std::vector
int main () {
// using std::find with array and pointer:
int myints[] = { 10, 20, 30, 40 ,30};
int * p;
p = std::find (myints, myints+5, 30);
if (p != myints+5)
std::cout << "数组下标是"<< (p - myints)<<"\nElement found in myints: " << *p << '\n';
else
std::cout << "Element not found in myints\n";
// using std::find with vector and iterator:
std::vector<int> myvector (myints,myints+4);
std::vector<int>::iterator it;
it = find (myvector.begin(), myvector.end(), 30);
if (it != myvector.end())
std::cout << "Element found in myvector: " << *it << '\n';
else
std::cout << "Element not found in myvector\n";
return 0;
}
如果只有这么简单,那么这篇博文也就没有什么参考价值了。先来看一下源码:
template<class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val)
{
while (first!=last) {
if (*first==val) return first;
++first;
}
return last;
}
我们会发现逻辑很简单,但是如果我们想将其运用到自己定义个类,我们就要自己重载“==”这个操作符啦,这样就会给我们更多的发挥空间啦。下面的代码是模拟的一个班级的成绩表,在成绩表中找到某个学生,以及他的各科成绩,注意“==”的重载。
// find example
#include <iostream> // std::cout
#include <algorithm> // std::find
#include <vector> // std::vector
using namespace std;
struct student{
string name;
float total;
float chinese;
float english;
float math;
};
bool operator== (student student_1,string str){
return student_1.name == str;
}
int main(){
vector<student> my_Class;
student zhangsan = {"张三",230,96,63,65};
my_Class.push_back(zhangsan);
student lisi = {"李四",230,97,75,85};
my_Class.push_back(lisi);
student wangwu = {"王五",240,75,67,65};
my_Class.push_back(wangwu);
student songliu = {"宋六",240,96,63,65};
my_Class.push_back(songliu);
student zhaoqi = {"赵七",240,96,63,66};
my_Class.push_back(zhaoqi);
vector<student>::iterator p = find(my_Class.begin(),my_Class.end(),"王五");
cout << p->name << "\n总分:" << p->total
<< "\n语文:" << p->chinese
<< "\n英语:" << p->english
<< "\n数学:" << p->math << endl;
return 0;
}
结果:
王五
总分:240
语文:75
英语:67
数学:65