如何在C++ 使用adjacent_find查询所有相邻重复元素?
例如:如何使下面的代码输出5和7?
```c++
#include
#include
#include
using namespace std;
// adjacent_find(iterator beg, iterator end);
// 查找相邻重复元素,返回相邻元素的第一个位置的迭代器
// beg 开始迭代器
// end 结束迭代器
void test01()
{
vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(0);
v.push_back(4);
v.push_back(5);
v.push_back(5);
v.push_back(7);
v.push_back(7);
v.push_back(5);
vector<int>::iterator pos = adjacent_find(v.begin(), v.end());
if (pos == v.end())
{
cout << "未查询到相关数据" << endl;
}
else
{
cout << "相邻重复元素: " << *pos << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
我的想法:利用仿函数,例如在下面的代码的 test01() 中利用仿函数 PrintIntGreater() 输出容器 vector 中所有大于5的元素。对于这个问题,是否可以用同样的思路来解决?如果可以,这个仿函数该怎么写呢?
#include
#include
#include
using namespace std;
// find_if(iterator beg, iterator end, _Pred);
// 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
// beg 开始迭代器
// end 结束迭代器
// _Pred 函数或者谓词(返回bool类型的仿函数)
class IntCompare
{
public:
bool operator()(int& val)
{
if (val > 5)
{
return true;
}
else
{
return false;
}
}
};
class PrintIntGreater
{
public:
void operator()(int& val)
{
if (val > 5)
{
cout << val << " ";
}
}
};
void test01()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>::iterator it = find_if(v.begin(), v.end(), IntCompare());
if (it == v.end())
{
cout << "未查询到数据" << endl;
}
else
{
cout << "查询到大于5的数:";
for_each(v.begin(), v.end(), PrintIntGreater());
cout << endl;
}
}
class Complex
{
public:
double real;
double imag;
Complex(double real, double imag)
{
this->real = real;
this->imag = imag;
}
};
class IsRealNumber
{
public:
bool operator()(const Complex& z)
{
return z.imag == 0.0;
}
};
class PrintRealNumber
{
public:
void operator()(const Complex& z)
{
if (z.imag == 0)
{
cout << z.real << " ";
}
}
};
void test02()
{
vector v;
Complex z1(1.5, -0.5);
Complex z2(1.5, 0.5);
Complex z3(0, 1.5);
v.push_back(z1);
v.push_back(z2);
v.push_back(z3);
vector::iterator it = find_if(v.begin(), v.end(), IsRealNumber());
if (it == v.end())
{
cout << "未找到数据" << endl;
}
else
{
cout << "找到实数: ";
for_each(v.begin(), v.end(), PrintRealNumber());
cout << endl;
}
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
首先排序,排序之后循环,判断和上一个是否一样。
不知道你这个问题是否已经解决, 如果还没有解决的话: