答案:C++中vector去重常用方法包括std::sort+std::unique(高效但排序)、std::unordered_set(保序且较快)、原地循环(小数据)和自定义类型处理,推荐优先使用std::sort+std::unique。

在C++中,对vector中的元素去重是一个常见需求。由于标准库没有提供直接的去重函数,通常需要结合std::sort和std::unique来实现。下面介绍几种常用且有效的去重方法。
这是最经典的方法,适用于基本类型(如int、double)或可以比较的自定义类型。
步骤如下:
std::sort将vector排序,使相同元素相邻std::unique将连续重复的元素移到末尾,并返回新的逻辑结尾迭代器erase删除多余元素
#include <vector>
#include <algorithm>
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5};
std::sort(vec.begin(), vec.end());
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
执行后,vec中元素为{1, 2, 3, 4, 5, 6, 9},无重复且有序。
立即学习“C++免费学习笔记(深入)”;
利用集合容器自动去重的特性,适合不想修改原顺序但不介意重新存储的情况。
std::set基于红黑树,元素有序std::unordered_set基于哈希表,查找更快
#include <unordered_set>
std::vector<int> vec = {3, 1, 4, 1, 5};
std::unordered_set<int> seen;
std::vector<int> result;
for (int x : vec) {
if (seen.insert(x).second) {
result.push_back(x);
}
}
vec = std::move(result);
这种方法能保持原始顺序,因为只保留第一次出现的元素。
对于很小的vector,可以直接双重循环判断是否已存在。
std::vector<int> result;
for (int x : vec) {
if (std::find(result.begin(), result.end(), x) == result.end()) {
result.push_back(x);
}
}
vec = std::move(result);
简单直观,但时间复杂度为O(n²),仅建议用于极小数据量。
如果vector中存储的是自定义结构体,需额外处理。
std::sort+std::unique:需提供比较函数或重载<
std::unordered_set:需提供哈希函数和==操作符例如:
struct Point {
int x, y;
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};
// 哈希特化
struct HashPoint {
size_t operator()(const Point& p) const {
return std::hash<int>{}(p.x) ^ std::hash<int>{}(p.y);
}
};
std::unordered_set<Point, HashPoint> seen;
基本上就这些常用方法。选择哪种取决于数据类型、是否要求保持顺序、性能要求等因素。std::sort + std::unique 是最通用高效的方案,推荐优先考虑。
以上就是c++++如何对vector中的元素去重_C++容器去重的多种实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号