去重c++ vector
时间: 2024-05-22 11:09:42 浏览: 14
在C++中,可以使用STL中的unique函数来实现去重。unique函数接受两个迭代器作为参数,将重复元素移到容器的尾部并返回新的尾部迭代器。再使用erase函数来删除重复元素即可。
以下是示例代码:
```
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> vec{1, 2, 3, 1, 4, 2, 5};
std::sort(vec.begin(), vec.end()); // 需要先进行排序
auto end = std::unique(vec.begin(), vec.end());
vec.erase(end, vec.end());
return 0;
}
```
相关问题
c++vector去重
C++中的vector是一个动态数组,可以存储不同类型的元素。如果你想要对vector进行去重操作,可以使用以下几种方法:
1. 使用set容器:将vector中的元素逐个插入到set容器中,由于set容器的特性是不允许重复元素存在,所以重复的元素会被自动去重。最后再将set容器中的元素重新放回vector中即可。
示例代码如下:
```cpp
#include <iostream>
#include <vector>
#include <set>
int main() {
std::vector<int> vec = {1, 2, 3, 2, 4, 3, 5};
std::set<int> uniqueSet(vec.begin(), vec.end());
vec.assign(uniqueSet.begin(), uniqueSet.end());
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
```
输出结果为:1 2 3 4 5
C++ vector去重
C++中对vector进行去重的方法有多种。其中一种方法是使用C++自带的remove函数。首先,需要包含头文件iostream、vector、algorithm和functional。然后,创建一个vector,并使用for循环将元素添加到vector中。接下来,使用remove函数将指定元素从vector中移除,再使用erase函数将移除的元素从vector中擦除。最后,使用for循环遍历vector并打印每个元素。
另一种去重方法是先对vector进行排序,然后使用unique函数去除重复元素,最后使用erase函数删除重复的元素。首先,需要包含头文件iostream、algorithm和vector。然后,创建一个int数组并将其转换为vector。接下来,使用sort函数对vector进行排序,然后使用unique函数去除重复元素,再使用erase函数删除重复的元素。最后,使用for循环遍历vector并打印每个元素。
还有一种方法是使用set的特性。首先,需要包含头文件iostream、vector和set。然后,创建一个int数组并将其转换为vector。接下来,使用set将vector中的元素去重,并将去重后的元素重新赋值给vector。最后,使用for循环遍历vector并打印每个元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)