Return vector::end()
,抛出异常或返回普通迭代器以外的其他内容
更好的是,不要实现自己的Find
功能。这就是<algorithm>
图书馆的用途。根据您的伪代码,您可能可以使用std::find
or std::find_if
。 find_if
在平等不一定意味着operator==
. 在这些情况下,您可以使用 [C++11] lambda,或者如果您无法使用 C++11,则可以使用仿函数类。
由于函子是最小的公分母,我将从以下开始:
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class Person
{
public:
Person(const string& name, unsigned age) : name_(name), age_(age) {};
string name_;
unsigned age_;
};
class match_name : public unary_function <bool, string>
{
public:
match_name(const string& rhs) : name_(rhs) {};
bool operator()(const Person& rhs) const
{
return rhs.name_ == name_;
}
private:
string name_;
};
#include <iostream>
int main()
{
vector<Person> people;
people.push_back(Person("Hellen Keller", 99));
people.push_back(Person("John Doe", 42));
/** C++03 **/
vector<Person>::const_iterator found_person = std::find_if( people.begin(), people.end(), match_name("John Doe"));
if( found_person == people.end() )
cout << "Not FOund";
else
cout << found_person->name_ << " is " << found_person->age_;
}
found_person
now 指向名为“John Doe”的人,否则指向people_.end()
是否找不到该人。
C++11 lambda 是一种新的语言语法,它使得声明/定义函子和使用的过程在许多情况下更加简单。它是这样完成的:
string target = "John Doe";
vector<Person>::const_iterator found_person = std::find_if(people.begin(), people.end(), [&target](const Person& test) { return it->name_ == target; });