
数组是 C++ 中可用的数据结构,用于保存相同类型元素的顺序集合。数组的大小是固定的,但可以根据需要扩展或缩小。将数组视为相同类型变量的集合很重要,即使它用于存储数据集合。集合(或者在本例中为无序集合)是一种以任意顺序存储特定数据类型的元素的容器。哈希表用于实现 unordered_set,其中键被哈希到哈希表索引中,以帮助确保插入始终是随机的。
可以使用我们进一步讨论的各种方法来完成从数组到无序集的转换。
将数组元素一一插入到集合中
将数组转换为无序集的最简单方法是使用 for 循环并将每个数组元素单独插入到无序集中。接下来我们看一下语法和算法。
语法
int ip[] = ; unordered_set op; for( int i : ip) { op.insert(i);}
算法
在整数数组 ip 中获取输入。定义一个 unordered_set 操作。对于数组 ip 中的每个元素 i,执行 -将 IP 插入 op。显示op的内容。
示例
#include using namespace std;template unordered_set solve( int (&ip)[N] ){ //an unorderd set is declared unordered_set 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 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);
算法
在整数数组 ip 中获取输入。使用 sizeof 运算符确定输入数组的大小。将数组的大小分配给整数变量 n。使用数组起始指针和数组大小构造一个 unordered_set 操作。显示op的内容。
示例
#include using namespace std;template unordered_set 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 op(ip, ip + n); return op;}int main(){ int ip[] = {30, 20, 50, 10, 70}; unordered_set 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++程序将数组转换为集合(哈希集合)的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1445296.html
微信扫一扫
支付宝扫一扫