本章描述C++泛型算法find的设计和使用。
我们先来看看C++官方网站上对find的描述
http://www.cplusplus.com/reference/algorithm/find/
(注:以下内容是我对C++官方网站上内容的理解,不准确的地方请见谅)
- find函数的声明:
template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val);
- find函数的作用:
在[first,last)范围内查找第一个与val相等的元素,并返回这个元素的迭代器(iterator),如果没有找到,则返回last。
- find函数的实现:
根据这个函数的实现,不难看出参数和返回值得类型,范围和使用方法,这里不再赘述。
有一点需要注意,从函数的实现上我们可以看到find函数使用operator==来对元素是否相等进行判断,所以,如果你需要比较的内容的元素类型是自定义类型,那么你必须重载operator==。
1 template<class InputIterator, class T> 2 InputIterator find (InputIterator first, InputIterator last, const T& val) 3 { 4 while (first!=last) 5 { 6 if (*first==val) return first; 7 ++first; 8 } 9 return last; 10 }
理论上的东西基本就这些,以下是我写的一个简单的例子
1 #include <algorithm> 2 3 #include <iostream> 4 #include <string> 5 #include <vector> 6 7 using std::cout; 8 using std::endl; 9 using std::string; 10 using std::vector; 11 12 void print(vector<string> vec) 13 { 14 vector<string>::iterator iter; 15 for (iter = vec.begin(); iter != vec.end(); iter++) 16 { 17 cout << *iter << " "; 18 } 19 cout << endl; 20 } 21 22 int main(void) 23 { 24 vector<string> vec; 25 vec.push_back("a"); 26 vec.push_back("b"); 27 vec.push_back("c"); 28 vec.push_back("d"); 29 print(vec); 30 31 vector<string>::iterator iter; 32 iter = find(vec.begin(), vec.end(), "c"); 33 if (iter != vec.end()) 34 { 35 cout << "found it: " << *iter << endl; 36 } 37 return 0; 38 }