要求
// 要求:将 str 中重复项去除
string str{"A1","A8","A2","A2","A8","A3","A1","A4"};
小二上代码
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // 包含此头文件
// 去除重复项并排序
void removeRepeat(std::vector<std::string> &items)
{
std::sort(items.begin(), items.end()); // 排序一下项,把相邻的项放在一起
auto end_unique = unique(items.begin(), items.end()); // 把重复的项放在最后
items.erase(end_unique, items.end()); // 去掉重复的项
}
// 主函数
int main()
{
std::vector<std::string> items{ "A1","A8","A2","A2","A8","A3","A1","A4" };
std::cout << std::endl << "去除重复项并排序前:";
for (auto item : items)
std::cout << item << " ";
removeRepeat(items); // 去除重复项并排序
std::cout << std::endl << "去除重复项并排序后:";
for (auto item : items)
std::cout << item << " ";
return 0;
}
调试结果:
_End
完事儿。