Go语言打印反转哈希集合的程序


在Go语言中,我们可以使用反向映射方法打印反转的哈希集合。哈希集合中,哈希映射以键值对的形式存储数据,从而减少了执行时间。在这篇文章中,我们将看到两个不同的例子,来了解如何创建一个Go语言程序来打印反转的哈希集合。

语法

func make ([] type, size, capacity)

Go语言中的`make`函数用于创建数组/映射,它接受要创建的变量类型、大小和容量作为参数。

func len(v Type) int

`len()`函数用于获取任何参数的长度。它接受一个参数作为要查找其长度的数据类型变量,并返回一个整数类型的长度值。

算法

  • 在程序中导入所需的包

  • 创建一个主函数

  • 在该函数中创建一个哈希映射

  • 然后,使用内部函数创建一个反转映射

  • 在控制台上打印反转映射

示例 1

在这个例子中,我们将创建一个哈希映射和一个名为`inverted`的附加映射,以获得反转的输出,即键分配给值。哈希映射将被迭代以在每次迭代中获得反转的输出。让我们了解这个例子,仔细看看代码和算法。

//Golang program to print the inverted hash collection
package main

import "fmt"

//Main to execute the program
func main() {
   // Create a map with keys of type string and values of type int
   hashmap := map[string]int{"apple": 100, "mango": 180, "banana": 120}
   
   // Create a new map with inverted keys and values
   inverted := make(map[int]string)
   for k, element := range hashmap {
      inverted[element] = k
   }
   
   // Print the inverted map
   fmt.Println("This is the following inverted map:")
   fmt.Println(inverted)
}

输出

This is the following inverted map:
map[100:apple 120:banana 180:mango]

示例 2

在这个例子中,我们将在`make`函数中使用`len(map)`来创建反转映射,该映射将用于存储反转的键值对。输出将是使用`fmt`包在控制台上打印的反转映射。让我们通过代码和算法来了解执行过程。

//Golang program to print the inverted hash collection
package main

import "fmt"

//Main function to execute the program
func main() {
   // Create a map with keys of type string and values of type int
   hashmap := map[string]int{"apple": 100, "mango": 120, "banana": 130}
   
   // Create a new map with inverted keys and values
   inverted := make(map[int]string, len(hashmap))
   for k, element := range hashmap {
      inverted[element] = k
   }
   
   // Print the inverted map
   fmt.Println("The inverted map is presented as follows:")
   fmt.Println(inverted)
}

输出

The inverted map is presented as follows:
map[100:apple 120:mango 130:banana]

结论

我们使用两个例子执行了打印反转哈希集合的程序。在第一个例子中,我们创建了不使用`len(hashmap)`的附加映射,而在第二个例子中,我们使用`len(hashmap)`函数创建了映射。

更新于:2023年3月27日

浏览量:121

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.