作者:Mr.龚
主题:删除容器中的重复元素
疑惑:
学习笔记详解: #include <iostream> #include <string> #include <algorithm>
using namespace std;
int main() { string s1 = "This is a test!"; sort(s1.begin(), s1.end()); cout << s1 << endl; string::iterator it = unique(s1.begin(), s1.end()); cout << s1 << endl; s1.erase(it, s1.end()); cout << s1 << endl; return 0; }
运行结果:
总结:① 利用 sort()+ unique() + erase()可以删除C++容器中的重复元素。 ② 在删除容器重复元素前,必须先调用sort()对容器进行排序,因为unique()函数只能查询到连续相邻的重复元素。 ③ unique()函数的作用是查找已排序容器中的重复元素并将结果按顺序排在原容器尾部,这里注意:unique()将重复元素排在原容器后面时,首先会删除重复序列中的“空格”字符元素。unique()返回值是重复序列起始位置,也就是原容器尾迭代器指示位置。 ④ erase(iterator a, iterator b):删除容器中迭代器a ~ b 之间的所有元素。 ⑤ vector向量容器的迭代器为:vector<元素类型>::iterator 迭代器变量; string字符串容器的迭代器为:string::iterator 迭代器变量。
|