学习stl有段时间了,总想写点什么,做点笔记,然后就开始纠结了是先写allocator, vector还是别的,最终决定柿子先挑软的捏,从算法开始吧,此为我的第一作,呵呵.
一个比较简单的find算法,先声明不是容器内部的算法,是一个泛型算法~~
在此先向<<stl源码剖析>>这本书致敬!
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
华丽的分割线
find()算法的用途主要是循环查找
//find.h template <class Iterator, class T> Iterator find(Iterator begin, Iterator end, const T &value) { while(begin != end && *begin != value) { ++begin; } return begin; }
测试程序
//main.cpp #include <iostream> #include "find.h" //#include <algorithm> #include <vector> #include <list> #include <set> #include <map> #include <string> #include <utility> using namespace std; int main(void) { int a[5] = {0, 1, 2, 3, 4}; vector<int> ivec(a, a+5); list<int> ilis(a, a+5); set<int> iset(a, a+5 ); map<int, string> imap; imap[0] = "jiang"; imap[1] = "ya"; imap[2] = "feng"; imap[3] = "a"; imap[4] = "hero"; int *p = find(a, a+5, 3); cout << *p << endl; //3 vector<int>::iterator iter1 = find(ivec.begin(), ivec.end(), 3); cout << *iter1 << endl; //3 list<int>::iterator iter2 = find(ilis.begin(), ilis.end(), 3); cout << *iter2 << endl; //3 set<int>::iterator iter3 = find(iset.begin(), iset.end(), 3); cout << *iter3 << endl; //3 /*map<int, string>::iterator iter4 = find(imap.begin(), imap.end(), make_pair(3, string("a")));*/ //error map<int, string>::iterator iter4 = find(imap.begin(), imap.end(), pair<const int, string>(3, string("a"))); cout << (*iter4).second << endl; // a system("pause"); return 0; }
map<int, string>::iterator iter4 = find(imap.begin(), imap.end(), make_pair(3, string("a")))是错误的,因为make_pair(3, string("a")) 生成 pair<int, string>而map中是 pair<const int, string>类型,所以不能比较!
故而用的是
map<int, string>::iterator iter4 = find(imap.begin(), imap.end(), pair<const int, string>(3, string("a")));