西西河

主题:借宝地问一个关于powerpoint -- 青牛甲

共:💬8 🌺1
全看分页树展 · 主题 跟帖
家园 呵,泰让兄最近总是解答问题哈,可否

呵,泰让兄最近总是解答问题哈,可否帮我看看这一行代码?

好久以前没事干,学学C++STL里东东,碰到一个问题,一直没有解决。今天想到了,想借机请教下:

search() 这个东东就是比较两个序列。这个函数有两个version,两者唯一不同的就是多了个比较的参数。而且代码也基本相同,但是我标记红颜色的那一行代码,我一直搞不懂多出来有什么用?(稍试了试,没它也行。而且逻辑上和上一行代码(我标蓝色)的功能是一样的)

version_1:

template <class _ForwardIter1, class _ForwardIter2>

_ForwardIter1 search(_ForwardIter1 __first1, _ForwardIter1 __last1,_ForwardIter2 __first2, _ForwardIter2 __last2)

{

// Test for empty ranges

if (__first1 == __last1 || __first2 == __last2)

return __first1;

// Test for a pattern of length 1.

_ForwardIter2 __tmp(__first2);

++__tmp;

if (__tmp == __last2)

return find(__first1, __last1, *__first2);

// General case.

_ForwardIter2 __p1, __p;

__p1 = __first2; ++__p1;

_ForwardIter1 __current = __first1;

while (__first1 != __last1) {

__first1 = find(__first1, __last1, *__first2);

if (__first1 == __last1) return __last1;

__p = __p1;

__current = __first1;

if (++__current == __last1)

return __last1;

while (*__current == *__p) {

if (++__p == __last2)

return __first1;

if (++__current == __last1)

return __last1;

}

++__first1;

}

return __first1;

}

version_2:

template <class _ForwardIter1, class _ForwardIter2, class _BinaryPred>

_ForwardIter1 search(_ForwardIter1 __first1, _ForwardIter1 __last1,_ForwardIter2 __first2, _ForwardIter2 __last2,

_BinaryPred __predicate)

{

// Test for empty ranges

if (__first1 == __last1 || __first2 == __last2)

return __first1;

// Test for a pattern of length 1.

_ForwardIter2 __tmp(__first2);

++__tmp;

if (__tmp == __last2) {

while (__first1 != __last1 && !__predicate(*__first1, *__first2))

++__first1;

return __first1;

}

// General case.

_ForwardIter2 __p1, __p;

__p1 = __first2; ++__p1;

_ForwardIter1 __current = __first1;

while (__first1 != __last1) {

while (__first1 != __last1) {

if (__predicate(*__first1, *__first2)) break;

++__first1;

}

while (__first1 != __last1 && !__predicate(*__first1, *__first2))

++__first1;

if (__first1 == __last1) return __last1;

__p = __p1;

__current = __first1;

if (++__current == __last1) return __last1;

while (__predicate(*__current, *__p)) {

if (++__p == __last2)

return __first1;

if (++__current == __last1)

return __last1;

}

++__first1;

}

return __first1;

}

全看分页树展 · 主题 跟帖


有趣有益,互惠互利;开阔视野,博采众长。
虚拟的网络,真实的人。天南地北客,相逢皆朋友

Copyright © cchere 西西河