c++ vector 去重
时间: 2023-09-12 14:04:00 浏览: 245
你可以使用STL中的`std::unique`函数来对一个`vector`进行去重操作。以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 2, 3, 3, 3, 4, 5, 5};
// 对vector进行去重
auto last = std::unique(nums.begin(), nums.end());
// 删除重复元素之后的部分
nums.erase(last, nums.end());
// 打印去重后的结果
for (const auto& num : nums) {
std::cout << num << " ";
}
return 0;
}
```
运行以上代码,输出结果为:`1 2 3 4 5`。这样,你就成功地对`vector`进行了去重操作。
相关问题
C++vector去重
C++中有多种方式可以从`vector`中去除重复元素。以下是两种常见的方法:
1. 利用`set`容器的特性去重[^1]:
```cpp
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main() {
vector<int> test={1,2,3,3,3,4,2,3,5,2,63,56,34,24};
set<int> s(test.begin(), test.end()); // 使用set自动去重并保持顺序
test.assign(s.begin(), s.end()); // 重新填充vector
for (int x : test)
cout << x << " ";
return 0;
}
```
2. 直接在vector内使用`unique()`函数去重:
```cpp
#include <iostream>
#include <vector>
#include <algorithm> // 包含unique函数
using namespace std;
int main() {
vector<int> test={1,2,3,3,3,4,2,3,5,2,63,56,34,24};
sort(test.begin(), test.end()); // 先排序以便unique生效
test.erase(unique(test.begin(), test.end()), test.end()); // 去除重复并更新end迭代器
for (int x : test)
cout << x << " ";
return 0;
}
```
这两种方法都能有效去除`vector`中的重复元素,第一种方法通过将vector转换为set实现去重,然后回填至vector;第二种方法则是直接在vector上操作,利用`unique()`找到连续的重复部分并删除。
c++ vector去重
你可以使用C++的标准库中的`std::set`来对`std::vector`进行去重操作。`std::set`是一个有序且不允许重复的容器,它会自动帮助你去除重复元素。以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <set>
int main() {
std::vector<int> nums = {1, 2, 3, 2, 4, 3, 5, 6, 1};
// 使用std::set对向量进行去重
std::set<int> uniqueSet(nums.begin(), nums.end());
// 将去重后的元素存回向量
nums.assign(uniqueSet.begin(), uniqueSet.end());
// 输出去重后的向量
for (const auto& num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
运行以上代码,输出结果为:`1 2 3 4 5 6`。这样就实现了对`std::vector`的去重操作。注意,使用`std::set`会改变元素的顺序,因为它是有序的容器。如果你需要保持原有顺序,可以使用其他方法,比如自定义去重函数或者使用其他数据结构。
阅读全文
相关推荐















