
数组是 C++ 中可用的数据结构,用于保存相同类型元素的顺序集合。数组的大小是固定的,但可以根据需要扩展或缩小。将数组视为相同类型变量的集合很重要,即使它用于存储数据集合。集合(或者在本例中为无序集合)是一种以任意顺序存储特定数据类型的元素的容器。哈希表用于实现 unordered_set,其中键被哈希到哈希表索引中,以帮助确保插入始终是随机的。
可以使用我们进一步讨论的各种方法来完成从数组到无序集的转换。
将数组转换为无序集的最简单方法是使用 for 循环并将每个数组元素单独插入到无序集中。接下来我们看一下语法和算法。
int ip[] = <integer array>;
unordered_set<int> op;
for( int i : ip) {
op.insert(i);
}
#include <bits/stdc++.h>
using namespace std;
template <size_t N> unordered_set<int> solve( int (&ip)[N] )
{
//an unorderd set is declared
unordered_set<int> op;
//each element is inserted using insert function
for(int i : ip) {
op.insert(i);
}
return op;
}
int main()
{
int ip[] = {50, 80, 90, 40, 30};
unordered_set<int> op = solve(ip);
//display the input
cout<< "The input array is: ";
for(int i : ip) {
cout<< i << " ";
}
//display the output
cout<< "\nThe output set is: ";
for(int j : op) {
cout<< j << " ";
}
return 0;
}
The input array is: 50 80 90 40 30 The output set is: 30 40 90 50 80
我们声明了一个整数数组 ip 并迭代数组中的所有元素。我们将输出集声明为 op,并使用容器中可用的插入函数将每个元素插入到无序集中。我们可以看到的结果是一组无序的值,这些值也存在于数组中。
立即学习“C++免费学习笔记(深入)”;
还可以使用其范围构造函数创建 unordered_set。范围构造函数有两个输入;输入数组的起始指针以及加上起始指针的输入数组的大小。
int ip[] = ; int n = sizeof(ip) / sizeof(ip[0]); std::unordered_set op(ip, ip + n);
#include <bits/stdc++.h>
using namespace std;
template <size_t N> unordered_set<int> solve(int (&ip)[N]) {
//the size is determined of the input array
int n = sizeof(ip) / sizeof(ip[0]);
//output set is constructed using range constructor
std::unordered_set<int> op(ip, ip + n);
return op;
}
int main()
{
int ip[] = {30, 20, 50, 10, 70};
unordered_set<int> op = solve(ip);
//display the input
cout<< "The input array is: ";
for(int i : ip) {
cout<< i << " ";
}
//display the output
cout<< "\nThe output set is: ";
for(int j : op) {
cout<< j << " ";
}
return 0;
}
The input array is: 30 20 50 10 70 The output set is: 70 10 50 20 30
在此示例中,我们必须使用 sizeof 函数确定数组的大小。我们 将大小分配给变量 n 并使用指针 ip 和 ip + n 创建 unordered_set 操作。
unordered_set 能够包含任何类型的数据。要更改它所保存的数据类型,我们必须更改 中包含的数据类型。该容器很好地支持原始类型和用户定义类型。实际上,unordered_set 工作得很好,通常提供恒定时间的搜索操作。 unordered_set 上的所有操作通常都需要恒定时间 O(1),尽管在最坏的情况下,它们可能需要长达线性时间 O(n),具体取决于内部哈希函数。
以上就是C++程序将数组转换为集合(哈希集合)的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号