【关键代码】
alls.erase(unique(alls.begin(), alls.end()), alls.end());
【代码】
#include <bits/stdc++.h>
using namespace std;
vector<int> alls; //整型数组
void test01()
{
alls.push_back(1);
alls.push_back(3);
alls.push_back(3);//重复
alls.push_back(4);
alls.push_back(5);
alls.push_back(6);
alls.push_back(6);//重复
for (auto x : alls) cout << x << ' ';
cout << endl;
alls.erase(unique(alls.begin(), alls.end()), alls.end());
for (auto x : alls) cout << x << ' ' ;
}
int main()
{
test01();
}
【解析】
这是erase()的第一个参数
unique(ans.begin(), ans.end())
unique(ans.begin(), ans.end())
: 这个函数模板位于<algorithm>头文件中,它接受两个迭代器参数,表示容器中要去除重复元素的范围。在这里,ans.begin()
表示容器的起始位置,ans.end()
表示容器的结束位置。unique
函数并不真正移除重复元素,它只是将重复的元素移到容器末尾,并返回一个指向不重复元素范围末尾的迭代器。erase
函数是容器的成员函数,用于从容器中删除元素。在这里,我们使用它来删除那些在调用unique
后位于末尾的重复元素。
erase(first,last);删除从first到last之间的字符(first和last都是迭代器)
1.first: unique(ans.begin(), ans.end())
unique
返回一个指向不重复元素范围末尾的迭代器。
2.end: alls.end()
返回指向数组结尾的迭代器。
3.erase:删除