卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章20392本站已运行347

C++程序将数组转换为集合(哈希集合)

<?xml encoding="utf-8" ?>

C++程序将数组转换为集合(哈希集合)

数组是 C++ 中可用的数据结构,用于保存相同类型元素的顺序集合。数组的大小是固定的,但可以根据需要扩展或缩小。将数组视为相同类型变量的集合很重要,即使它用于存储数据集合。集合(或者在本例中为无序集合)是一种以任意顺序存储特定数据类型的元素的容器。哈希表用于实现 unordered_set,其中键被哈希到哈希表索引中,以帮助确保插入始终是随机的。

可以使用我们进一步讨论的各种方法来完成从数组到无序集的转换。

将数组元素一一插入到集合中

将数组转换为无序集的最简单方法是使用 for 循环并将每个数组元素单独插入到无序集中。接下来我们看一下语法和算法。

语法

int ip[] = <integer array>;
   unordered_set<int> op;
   for( int i : ip) {
      op.insert(i);
}

算法

  • 在整数数组 ip 中获取输入。
  • 定义一个 unordered_set 操作。
  • 对于数组 ip 中的每个元素 i,执行 -
    • 将 IP 插入 op。
  • 显示op的内容。

示例

#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,并使用容器中可用的插入函数将每个元素插入到无序集中。我们可以看到的结果是一组无序的值,这些值也存在于数组中。

使用范围构造函数构造集合

还可以使用其范围构造函数创建 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 <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# 支持哪些不同类型的条件语句?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏