gpt4 book ai didi

go - 它不是以要求的格式打印,而是以无序格式打印

转载 作者:数据小太阳 更新时间:2023-10-29 03:43:48 27 4
gpt4 key购买 nike

package main

import (
"fmt"
"bufio"
"os"
"strconv"
)
func main() {
mp := make(map[int]string)//make a mapping
in := bufio.NewScanner(os.Stdin)
fmt.Println("Limit and Enter Strings")
in.Scan()
n := in.Text()
num, err := strconv.Atoi(n)
fmt.Println(err)
for i:=0; i<=num;i++ {
in.Scan()
mp[i] = in.Text()
}
fmt.Println(mp)
}
/* Output Limit and Enter Strings
5
<nil>
one
two
three
four
five
six
map[3:four 4:five 5:six 0:one 1:two 2:three]*/

该程序用于从 int 到 string 的映射。当我以顺序格式输入数字时,它会以错误的顺序打印映射。

最佳答案

Go provides a built-in map type that implements a hash table.

When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. If you require a stable iteration order you must maintain a separate data structure that specifies that order. This example uses a separate sorted slice of keys to print a map[int]string in key order:

导入“排序”

var m map[int]string
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}

链接:https://blog.golang.org/go-maps-in-action

关于go - 它不是以要求的格式打印,而是以无序格式打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51184308/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com