难道是 c++ 中的 find_end() 有 BUG?

// 以下是 wrong.cpp。那里出问题了?难道是 c++ 中的 find_end() 有 BUG?

#include
#include
#include
bool equals ( int elem1, int elem2 )
{
return 2 * elem1 == elem2;
}
int main(int argc,char *argv] )
{
using namespace std;
vector v1, v2;
vector ::iterator Iter1, Iter2;
int i;
for ( i = 0 ; i <= 5 ; i++ )
{
v2.push_back( 5 * i );
}
int iii;
for ( iii = 0 ; iii <= 11 ; iii++ )
{
v1.push_back(iii);
}

cout << "Vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << “)” << endl;
cout << "Vector v2 = ( " ;
for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ )
cout << *Iter2 << " ";
cout << “)” << endl;

vector ::iterator result;
result = find_end ( v1.begin( ), v1.end( ), v2.begin( ), v2.end( ), equals );;

if ( result == v1.end( ) )
cout << “There is no match of v2 in v1.”
<< endl;
else
cout << "There is a sequence of elements in v1 that "
<< "are equivalent to those
in v2 under the binary "
<< "predicate twice and that begins at position "
<< result - v1.begin( ) << “.” <<endl;
}
/*
suse@linux-qmfx:~/program> g++ -o wrong up.cpp
suse@linux-qmfx:~/program> ./wrong
Vector v1 = ( 0 1 2 3 4 5 6 7 8 9 10 11 )
Vector v2 = ( 0 5 10 15 20 25 )
There is no match of v2 in v1.
suse@linux-qmfx:~/program>
#v1 中的 10 、5 为什么找不出来?
*/

你对 find_end() 理解有误,find_end() 是在一个序列中搜索出最后一个与另一序列匹配的子序列。

在你的程序中
Vector v1 = ( 0 1 2 3 4 5 6 7 8 9 10 11 )
Vector v2 = ( 0 5 10 15 20 25 )

而你的比较函数为
bool equals ( int elem1, int elem2 )
{
return 2 * elem1 == elem2;
}

所以实际上是将下面两个 vector 比较
Vector v1 = ( 0 2 4 6 8 10 12 14 16 18 20 22 )
Vector v2 = ( 0 5 10 15 20 25 )

在 v1 中没有子序列为 0 5 10 15 20 25 ,你当然找不到。

贴一段别人写的程序

#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

int main()
{
	vector<int> v1;
	v1.push_back(5);
	v1.push_back(-2);
	v1.push_back(4);
	v1.push_back(3);
	v1.push_back(-2);
	v1.push_back(4);
	v1.push_back(8);
	v1.push_back(-2);
	v1.push_back(4);
	v1.push_back(9);

	vector<int>::const_iterator iter;
	cout << "v1: " ;
	for (iter = v1.begin(); iter != v1.end(); ++iter)
	{
		cout << *iter << "  ";
	}
	cout << endl;

	vector<int> v2;
	v2.push_back(-2);
	v2.push_back(4);

	cout << "v2: " ;
	for (iter = v2.begin(); iter != v2.end(); ++iter)
	{
		cout << *iter << "  ";
	}
	cout << endl;

	vector<int>::iterator iLoaction;
	iLoaction = find_end(v1.begin(), v1.end(), v2.begin(), v2.end());

	if (iLoaction != v1.end())
	{
		cout << "v1 中找到最后一个匹配 V2 的子序列,起始位置在:"
			 << "v1" << iLoaction - v1.begin() << "]" << endl;
	}

	return 0;
}

你先运行一下,然后在 v2 后面再 push_back 一个数,再运行,比较一下结果。