想要去除容器中的重复元素,可以用STL提供的函数std::unique。
与stl的其他删除函数类似,该函数并没有真正删除重复元素,只是移动了元素的位置,返回需要删除的逻辑位置。
除此之外,std::unique只能去除相邻的重复元素。
什么意思呢?请看下面代码:
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
list<int> lstInt = { 1, 2, 4, 8, 2, 2, 3, 4, 5, 8, 10, 2 };
lstInt.erase(std::unique(lstInt.begin(), lstInt.end()), lstInt.end());
for (const auto i : lstInt)
cout << i << " ";
cout << endl;
system("pause");
return 0;
}
执行结果如下:
仅仅重复出现的“2”被删除了!
想要删除所有重复元素,改怎么做的?
先排序!再去重!
list有一个成员函数sort,可以实现对其自身的排序,默认是通过小于号“<”来比较,也可以自定义排序规则。
修改后代码如下:
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
list<int> lstInt = { 1, 2, 4, 8, 2, 2, 3, 4, 5, 8, 10, 2 };
lstInt.sort(); //先排序
lstInt.erase(std::unique(lstInt.begin(), lstInt.end()), lstInt.end());
for (const auto i : lstInt)
cout << i << " ";
cout << endl;
system("pause");
return 0;
}
执行结果如下:
其他容器类似。
但是需要注意一点,对于vector、array等,并没有排序的成员函数。可以使用STL提供的排序算法std::sort,代码如下:
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
vector<int> vecInt = { 1, 2, 4, 8, 2, 2, 3, 4, 5, 8, 10, 2 };
std::sort(vecInt.begin(), vecInt.end()); //利用STL的排序算法实现对vector的排序
vecInt.erase(std::unique(vecInt.begin(), vecInt.end()), vecInt.end());
for (const auto i : vecInt)
cout << i << " ";
cout << endl;
system("pause");
return 0;
}
执行结果如下: