我想使用哈希图打印非重复的数字;

i want to print the non repeated number using hashmap;

本文关键字:数字 打印 哈希图      更新时间:2023-10-16
// Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector<int> printNonRepeated(int arr[], int n);
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
vector<int> v;
v = printNonRepeated(arr, n);
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends
// Function to print the non repeated elements in the array
// arr[]: input array
// n: size of array
vector<int> printNonRepeated(int arr[], int n) {
vector<int> a;
unordered_map<int, int> h;
int count = 0;
int i;
for (i = 0; i < n; i++) {
h[arr[i]]++;
}
int j = 0;
for (auto x : h) {
if (x.second == 1) {
a[j] = x.first;
j++;
}
}
return a;
}

我想使用函数vector<int> printNonRepeated(int arr[],int n)打印非重复数字。我正在尝试使用哈希图。我在编译时遇到分段错误。我哪里做错了。 我没有更改主功能的权限。我只能更改"打印非重复"功能。

a[j] = x.first;
j++;

如果不先分配空间,则无法访问a的第j个索引。数组的大小需要预定义,或者您可以使用push_back以便向量在末尾添加新元素。

a.push_back(x.first);

对于初学者可变长度数组,如下所示

int n;
cin >> n;
int arr[n];

不是标准的C++功能。

不能将下标运算符与空向量一起使用。

vector<int> a;
//...
for (auto x : h) {
if (x.second == 1) {
a[j] = x.first;
j++;
}

创建矢量是多余的。最初可以将输入的值存储在 main 中声明std::map类型的容器中。