Golang 打印反转的哈希集合
在Golang中,我们可以使用反转映射方法打印反转的哈希集合。哈希集合中的哈希图存储数据对 key:Value,这将减少执行时间。在本文中,我们将看到两个不同的示例,以了解如何创建一个能够打印反转的哈希集合的Golang程序。
语法
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
在这个示例中,我们将在制作函数中使用len(map)来创建倒转的map,它将用于存储倒转的键值对。输出将会是一个倒转的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)函数来创建映射。