c++数组去重并打印
时间: 2023-12-20 22:31:44 浏览: 30
以下是一种C++数组去重并打印的方法:
```cpp
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
unordered_set<int> uniqueElements;
for (int i = n - 1; i >= 0; i--) {
if (uniqueElements.find(arr[i]) == uniqueElements.end()) {
uniqueElements.insert(arr[i]);
}
}
cout << uniqueElements.size() << endl;
for (auto it = uniqueElements.begin(); it != uniqueElements.end(); it++) {
cout << *it << " ";
}
cout << endl;
return 0;
}
```
相关问题
C++语言两个数组去重合并
您好,以下是 C 语言实现两个数组去重合并的示例代码:
```c
#include <stdio.h>
// 判断元素是否已经存在于目标数组中,存在返回1,不存在返回0
int exist(int a[], int n, int x){
for(int i=0; i<n; i++){
if(a[i] == x) return 1;
}
return 0;
}
// 将数组b中的元素添加到数组a中
void merge(int a[], int *n, int b[], int m){
for(int i=0; i<m; i++){
if(!exist(a, *n, b[i])){
a[(*n)++] = b[i];
}
}
}
int main(){
int a[100], b[100], n, m;
printf("输入数组a的长度(大于0小于等于100):");
scanf("%d", &n);
printf("输入数组a:");
for(int i=0; i<n; i++){
scanf("%d", &a[i]);
}
printf("输入数组b的长度(大于0小于等于100):");
scanf("%d", &m);
printf("输入数组b:");
for(int i=0; i<m; i++){
scanf("%d", &b[i]);
}
merge(a, &n, b, m);
printf("去重合并后的数组为:");
for(int i=0; i<n; i++){
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
```
该程序首先从标准输入获取两个数组的长度和元素值,然后通过 `exist` 函数判断每个元素是否在目标数组中存在,在不存在时添加到目标数组末尾,并最后输出去重合并后的目标数组。
用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
```