dqfxao2898 2019-01-16 19:36
浏览 1
已采纳

转到映射键循环的++运算符

I am following the Go tutorial here https://tour.golang.org/moretypes/23 and have modified the exercise a little bit to try to dig deeper.

package main

import (
    "fmt"
    "strings"
)

func WordCount(s string) map[string]int {
    m := make(map[string]int)
    x := strings.Fields(s)
    for _, e := range x {
        m[e]++
    }

    return m
}

func main() {
    phrase := "The quick brown fox"
    fmt.Println(WordCount(phrase), "length:", len(WordCount(phrase)))
}

What doesn't make sense to me is how the ++ operator works in this context when adding new elements to the map.

Definition of ++ operator: Increment operator. It increases the integer value by one.

In this context, the ++ operator increasing the integer value of the LENGTH of the map and then adding the e element to the new map length?

  • 写回答

1条回答 默认 最新

  • downloadbooks_2014 2019-01-16 19:45
    关注

    The default value of int values in a map is 0. So, when you iterate through x and call m[e]++, the expanded version would be

    m[e] = m[e] + 1
    

    In other words:

    m[e] = 0 + 1
    

    Of course, if a field repeats, it will already be in the map (with some value > 0).

    When you check the length of the map after the loop, it gives the number of unique fields in the string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器