std::vector 合并 去重
时间: 2023-08-25 21:16:29 浏览: 305
要使用std::vector合并并去重,可以使用insert()函数将多个vector插入到一个vector中,然后使用sort()函数进行排序,最后使用unique()函数和erase()函数删除重复项。以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> a{ 1,3,5,7,9 };
vector<int> b{ 0,4,8,2,5 };
vector<int> c{ 1,6,7,3,8 };
vector<int> merged;
merged.insert(merged.end(), a.begin(), a.end()); // 将a插入merged
merged.insert(merged.end(), b.begin(), b.end()); // 将b插入merged
merged.insert(merged.end(), c.begin(), c.end()); // 将c插入merged
sort(merged.begin(), merged.end()); // 对merged进行升序排序
vector<int>::iterator iter = unique(merged.begin(), merged.end()); // 查找并删除重复项
merged.erase(iter, merged.end());
cout << "合并并删除重复项后的size = " << merged.size() << endl;
if (merged.size() > 0) {
cout << "分别为:" << endl;
for (int i = 0; i < merged.size(); i++) {
cout << merged[i << endl;
}
}
return 0;
}
```
输出结果为:
```
合并并删除重复项后的size = 11
分别为:
0
1
2
3
4
5
6
7
8
9
```<em>1</em><em>2</em><em>3</em>
#### 引用[.reference_title]
- *1* [C++ vector数据合并&&去除重复项](https://blog.csdn.net/Gary_ghw/article/details/125633718)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
- *2* [C++ 给vector去重的三种方法](https://blog.csdn.net/u011089523/article/details/110122568)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
- *3* [c++ STL顺序容器vector/关联容器map的合并](https://blog.csdn.net/appleskyaaaa/article/details/119078701)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
[ .reference_list ]
阅读全文