adjacent_find: 查找容器中,相等的相邻元素。
这里的相等,并不一定是真的完全相同,这里的相等可以是自定义的等价关系。例如:定义如果第二个数是第一个数的2倍,则认为是“相等”:
#include <iostream>
#include <algorithm>
using namespace std;
// 定义等价关系:第二个数是第一个的2倍
class Twice
{
public:
bool operator()(int val1, int val2)
{
return val1*2==val2;
}
};
int main(void)
{
const int ARRAY_SIZE=8;
int IntArray[ARRAY_SIZE]={1, 2, 3, 4, 5, 6, 7, 8};
int* location=NULL;
cout<<"原始数据:"<<endl;
for(int i=0; i<ARRAY_SIZE; i++)
{
cout<<IntArray[i]<<" ";
}
cout<<endl;
location=adjacent_find(IntArray, IntArray+ARRAY_SIZE, Twice());
if(location != IntArray+ARRAY_SIZE)
{
cout<<"找到了等价元素:("<<*location<<", "<<*(location+1)<<")"<<endl;
}
else
{
cout<<"没有找到等价元素"<<endl;
}
return 0;
}
本文介绍了一个C++标准库函数adjacent_find的使用方法,通过一个示例程序展示了如何使用自定义等价关系来查找容器中相邻且相等的元素。等价关系由用户自定义,示例中定义了若第二个元素是第一个元素两倍则视为相等。
94

被折叠的 条评论
为什么被折叠?



