我想使用哈希图打印非重复的数字;
i want to print the non repeated number using hashmap;
// 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
类型的容器中。
相关文章:
- 打印数字图案
- 将数字打印成文字
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 我的问题是关于C++中数字和序列的重复以及如何打印它们?
- 编译器始终打印十六进制/八进制数字
- 我想使用哈希图打印非重复的数字;
- 如何在控制台上打印出带有数字 0-99 的简单数组
- 错误含义;以二进制形式打印数字
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 列中打印数字时如何避免打印垃圾?
- 如何编写一个程序来打印特定基数的前N个数字
- C++ 在地板函数之后以十六进制打印数字
- C 不将重复数字打印到输出
- 阿姆斯特朗数字打印错误
- 用数字打印所有可能的组合
- 将数字打印为字符串类型的数字
- 如何以特定格式将数字打印到字符串的中间
- 如何将矢量中的数字打印到文件中