【发布时间】:2021-07-08 14:19:34
【问题描述】:
任何人都可以向我解释 STL C++ 中无序集的这种逻辑,因为我是这个概念的新手。
他们如何使用无序集打印数组的缺失元素。
这种方法是否有效或有任何其他方法比这种方法有效。
逻辑如下:
for (int x = low; x <= high; x++)
if (s.find(x) == s.end())
cout << x << " ";
完整代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include <unordered_set>
using namespace std;
void printMissing(int arr[], int n, int low,int high)
{
unordered_set<int> s;
for (int i = 0; i < n; i++)
s.insert(arr[i]);
// Traverse throught the range an print all
// missing elements
for (int x = low; x <= high; x++)
if (s.find(x) == s.end())
cout << x << " ";
}
int main()
{
int arr[] = { 1, 3, 5, 4, 2, 8, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int low = 1, high = 10;
printMissing(arr, n, low, high);
return 0;
}
【问题讨论】:
-
他们将所有数组元素添加到集合中,然后遍历一个范围并打印不在集合中的数字。您有更具体的问题吗?
标签: c++ arrays c++14 hashtable unordered-set