标签:des style blog http color 2014
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
search
-------------------------------------------------------------------------源码:
template <class ForwardIterator1, class ForwardIterator2> inline ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { return __search(first1, last1, first2, last2, distance_type(first1), distance_type(first2)); } //没看源码之前,还以为会有什么复杂的算法,结果也只是遍历 //如果没有假设(比如有序什么的),STL里的许多算法实现也是挺普通的做法 template <class ForwardIterator1, class ForwardIterator2, class Distance1, class Distance2> ForwardIterator1 __search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, Distance1*, Distance2*) { Distance1 d1 = 0; distance(first1, last1, d1); Distance2 d2 = 0; distance(first2, last2, d2); if (d1 < d2) return last1; //如果第二序列大于第一序列,不可能成为其子序列 ForwardIterator1 current1 = first1; ForwardIterator2 current2 = first2; while (current2 != last2) // 我的第一感觉是遍历第一序列,结果人家是遍历第二序列。不过感觉代码写起来应该差不多 if (*current1 == *current2) { // 如果这个元素相同,调整,以便比对下一个元素 ++current1; ++current2; } else { //如果这个元素不同 if (d1 == d2) //如果两序列一样长了,就不可能成功了 return last1; else { //如果两序列不一样长,调整序列标兵 current1 = ++first1; current2 = first2; --d1; //已经排序了序列一的一个元素,所以序列一的长度要减 1 } } return first1; }
const char S1[] = "Hello, world!"; const char S2[] = "world"; const int N1 = sizeof(S1) - 1; const int N2 = sizeof(S2) - 1; const char* p = search(S1, S1 + N1, S2, S2 + N2); printf("Found subsequence \"%s\" at character %d of sequence \"%s\".\n", S2, p - S1, S1);
STL 源码剖析 算法 stl_algo.h -- includes,布布扣,bubuko.com
STL 源码剖析 算法 stl_algo.h -- includes
标签:des style blog http color 2014
原文地址:http://blog.csdn.net/zhengsenlie/article/details/37932491