Go语言的map以及sort

来源:互联网 发布:淘宝店铺装修模块对齐 编辑:程序博客网 时间:2024/06/03 18:30

通过这个例子了解map的使用。


Go语言程序:

// map project main.gopackage mainimport ("fmt""sort")func main() {var countryCapitalMap map[string]string/* 创建集合 */countryCapitalMap = make(map[string]string)/* map 插入 key-value 对,各个国家对应的首都 */countryCapitalMap["France"] = "Paris"countryCapitalMap["Italy"] = "Rome"countryCapitalMap["Japan"] = "Tokyo"countryCapitalMap["India"] = "New Delhi"countryCapitalMap["China"] = "Beijing"fmt.Println("Original:")/* 使用 key 输出 map 值 */for country := range countryCapitalMap {fmt.Println("Capital of", country, "is", countryCapitalMap[country])}fmt.Println("")/* map 删除 key-value 对 */delete(countryCapitalMap, "India")fmt.Println("After deletion:")/* 使用 key 输出 map 值 */for country := range countryCapitalMap {fmt.Println("Capital of", country, "is", countryCapitalMap[country])}fmt.Println("")/* 映射反转 */capitalCountryMap := make(map[string]string, len(countryCapitalMap))for country, capital := range countryCapitalMap {capitalCountryMap[capital] = country}fmt.Println("After the reversal:")for capital := range capitalCountryMap {fmt.Println("Country of", capital, "is", capitalCountryMap[capital])}fmt.Println("")/* 查看元素在集合中是否存在 */captial, ok := countryCapitalMap["United States"]/* 如果 ok 是 true, 则存在,否则不存在 */if ok {fmt.Println("Capital of United States is", captial)} else {fmt.Println("Capital of United States is not present")}fmt.Println("")/* 排序输出 */var keys []stringfor k := range countryCapitalMap {keys = append(keys, k)}sort.Strings(keys)for _, k := range keys {fmt.Println("Key:", k, "Value:", countryCapitalMap[k])}}
 

程序运行结果:

Original:Capital of France is ParisCapital of Italy is RomeCapital of Japan is TokyoCapital of India is New DelhiCapital of China is BeijingAfter deletion:Capital of France is ParisCapital of Italy is RomeCapital of Japan is TokyoCapital of China is BeijingAfter the reversal:Country of Paris is FranceCountry of Rome is ItalyCountry of Tokyo is JapanCountry of Beijing is ChinaCapital of United States is not presentKey: China Value: BeijingKey: France Value: ParisKey: Italy Value: RomeKey: Japan Value: Tokyo

程序说明:

1.map似乎可以直接使用

2.排序可以使用sort包

3.map是无序的需要另外定义一个数组来排序


参考链接:

1.Ubuntu安装Go语言环境

2.Ubuntu构筑LiteIDE的Go语言开发环境



原创粉丝点击