答案:删除vector重复值常用三种方法:1. std::sort配合std::unique去重并排序;2. std::set自动去重但不保序,std::unordered_set辅助remove_if可保留顺序;3. 自定义类型需提供比较逻辑,重载==或传入比较函数。

在C++中删除vector中的重复值,可以通过几种常见方式实现,核心思路是先排序再去重,或使用集合类辅助。下面介绍几种实用且高效的方法。
1. 使用 std::sort 和 std::unique 配合
这是最常用、效率较高的方法。std::unique会将相邻的重复元素“前移”,并返回一个指向新逻辑结尾的迭代器,之后用erase删除多余部分。
示例代码:
#include
#include
#include iostream>
std::vector
std::sort(vec.begin(), vec.end()); // 排序
vec.erase(std::unique(vec.begin(), vec.end()), vec.end()); // 去重
// 输出结果:1 2 3 4 5
for (int x : vec) std::cout
2. 利用 std::set 或 std::unordered_set 自动去重
如果不需要保持原始顺序,可以将vector元素插入set中,自动去除重复。若要保留原始顺序,可用unordered_set做查重标记。
保留唯一性(不保序):
std::vector
std::set
vec.assign(s.begin(), s.end()); // 赋回去重后数据
std::vector
std::unordered_set
auto newEnd = std::remove_if(vec.begin(), vec.end(), [&seen](const int& value) {
if (seen.count(value)) return true;
seen.insert(value);
return false;
});
vec.erase(newEnd, vec.end());
3. 处理自定义类型(如结构体)的去重
对于结构体或类对象,需提供比较逻辑。可重载==操作符,或在sort和unique中传入比较函数。
立即学习“C++免费学习笔记(深入)”;
示例:
struct Point { int x, y; };
bool operator==(const Point& a, const Point& b) {
return a.x == b.x && a.y == b.y;
}
auto eq = [](const Point& a, const Point& b) {
return a.x == b.x && a.y == b.y;
};
std::sort(vec.begin(), vec.end(), [](const Point& a, const Point& b) {
return a.x
});
vec.erase(std::unique(vec.begin(), vec.end(), eq), vec.end());
基本上就这些。根据是否需要保持顺序、数据类型和性能要求选择合适方法。std::sort + std::unique 最通用,set适合小数据,unordered_set配合remove_if适合保留顺序的大数据场景。











