数组去重排序 c++
时间: 2025-04-01 20:03:23 浏览: 34
### 使用 C++ 对数组进行去重和排序
在 C++ 中,可以采用多种方式来实现数组的去重和排序功能。以下是两种常见的方法:
#### 方法一:利用 `std::set` 实现去重和排序
`std::set` 是 STL 提供的一种容器,其底层基于红黑树实现,具有自动排序和去重的特点[^1]。通过将数组中的元素插入到 `std::set` 容器中,即可轻松完成去重和排序。
下面是一个完整的代码示例:
```cpp
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main() {
vector<int> arr = {4, 2, 7, 2, 8, 4}; // 示例数组
set<int> uniqueSet(arr.begin(), arr.end()); // 利用 set 自动去重和排序
cout << "去重并排序后的结果:" << endl;
for (const auto& elem : uniqueSet) {
cout << elem << " ";
}
return 0;
}
```
上述代码中,我们将原始数组的数据范围映射至 `std::set` 的迭代器范围内,从而实现了自动去重和排序的功能。
---
#### 方法二:结合 `std::sort` 和 `std::unique`
另一种常用的方式是先对数组进行排序,然后再使用 `std::unique` 函数去除相邻的重复项[^3]。需要注意的是,`std::unique` 只能移除连续的重复元素,因此必须先调用 `std::sort` 进行预处理。
下面是具体实现代码:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> arr = {4, 2, 7, 2, 8, 4}; // 示例数组
sort(arr.begin(), arr.end()); // 排序
arr.erase(unique(arr.begin(), arr.end()), arr.end()); // 去重
cout << "去重并排序后的结果:" << endl;
for (const auto& elem : arr) {
cout << elem << " ";
}
return 0;
}
```
此方法的核心在于 `std::sort` 负责排列数组顺序,而 `std::unique` 将所有相邻的重复元素移动到数组末尾,并返回指向新序列结束位置的迭代器。随后可以通过 `erase` 删除多余部分。
---
以上两种方法均能够高效地解决数组去重和排序的问题。如果需要保留原数组不变,则推荐使用 `std::set`;若希望直接修改原有数组,则可以选择 `std::sort` 结合 `std::unique` 的方案。
阅读全文
相关推荐


















