c++如何对vector中的元素去重_C++容器去重的多种实现方法

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

在C++中,对vector中的元素去重是一个常见需求。由于标准库没有提供直接的去重函数,通常需要结合std::sortstd::unique来实现。下面介绍几种常用且有效的去重方法。

1. 使用 std::sort + std::unique(适用于可排序类型)

这是最经典的方法,适用于基本类型(如int、double)或可以比较的自定义类型。

步骤如下:

  • 先用std::sort将vector排序,使相同元素相邻
  • 再用std::unique将连续重复的元素移到末尾,并返回新的逻辑结尾迭代器
  • 最后调用erase删除多余元素
#include 
#include 

std::vector 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},无重复且有序。

2. 利用 std::set 或 std::unordered_set(保持插入顺序较难)

利用集合容器自动去重的特性,适合不想修改原顺序但不介意重新存储的情况。

  • std::set基于红黑树,元素有序
  • std::unordered_set基于哈希表,查找更快
#include 
std::vector vec = {3, 1, 4, 1, 5};
std::unordered_set seen;
std::vector result;

for (int x : vec) {
    if (seen.insert(x).second) {
        result.push_back(x);
    }
}
vec = std::move(result);

这种方法能保持原始顺序,因为只保留第一次出现的元素。

3. 原地去重(仅适用于小规模数据)

对于很小的vector,可以直接双重循环判断是否已存在。

std::vector 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²),仅建议用于极小数据量。

4. 自定义类型的去重方法

如果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{}(p.x) ^ std::hash{}(p.y);
    }
};

std::unordered_set seen;

基本上就这些常用方法。选择哪种取决于数据类型、是否要求保持顺序、性能要求等因素。std::sort + std::unique 是最通用高效的方案,推荐优先考虑。