用erase和unique实现数组去重
时间: 2023-05-10 11:55:34 浏览: 67
可以使用以下代码实现数组去重:
```
#include <algorithm>
#include <vector>
std::vector<int> uniqueArray(std::vector<int> arr) {
arr.erase(std::unique(arr.begin(), arr.end()), arr.end());
return arr;
}
```
这个函数接受一个整数类型的数组,使用 `std::unique` 函数将重复的元素移到数组末尾,然后使用 `std::vector::erase` 函数将这些重复元素从数组中删除。最后返回去重后的数组。
相关问题
用C++写一个数组去重
下面是一个简单的C++代码,使用了STL中的vector来存储去重后的数组元素:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 2, 4, 1, 5, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
vector<int> v(arr, arr + n);
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
cout << "去重后的数组为:";
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
去重后的数组为:1 2 3 4 5
```
两个数组去重合并排序C++
对于两个数组去重合并排序的问题,可以按照以下步骤来实现:
1. 首先将两个数组合并成一个数组
2. 对这个数组进行去重操作,保留每个元素的第一次出现的位置
3. 对去重后的数组进行排序
以下是C++代码示例:
```
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> merge_sort(vector<int>& nums1, vector<int>& nums2) {
vector<int> merged(nums1.size() + nums2.size());
merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), merged.begin());
return merged;
}
vector<int> unique_sort(vector<int>& nums) {
sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end());
return nums;
}
int main() {
vector<int> nums1 = {1, 3, 5, 7, 9};
vector<int> nums2 = {2, 4, 6, 8, 10};
vector<int> merged = merge_sort(nums1, nums2);
vector<int> result = unique_sort(merged);
// 输出去重后的排序结果
for (auto num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)