一、Map的定义
1.map[K]V
示例1:
m := map[string]string{
"name": "cpp",
"teacher": "radiomen",
}
fmt.Println(m)
示例2:
m2 := make(map[string]int) // m2 == empty map
fmt.Println(m2)
示例3:
var m3 map[string]int // m3 == nil
fmt.Println(m3)
2.复合map的定义
map[K1]map[K2]V
二、map的遍历
1.使用range遍历key,或者遍历key,value对
2.不保证遍历顺序,如果顺序,需手动对key排序
3.使用len获取元素的个数
示例4:
m := map[string]string{
"name": "cpp",
"teacher": "radiomen",
}
fmt.Println(m)
for k, v := range m{
fmt.Println(k, v)
}
三、获取元素
1.获取元素:m[key]
2.key不存在时,获得Value类型的初始值
3.判断map的key是否存在
示例5:
m := map[string]string{
"name": "cpp",
"teacher": "radiomen",
}
fmt.Println(m)
if name, ok := m["nam"]; ok{
fmt.Println(name)
} else {
fmt.Println("key does not exist")
}
四、删除元素
示例6:
m := map[string]string{
"name": "cpp",
"teacher": "radiomen",
}
fmt.Println(m)
if name, ok := m["name"]; ok{
fmt.Println(name)
delete(m, "name")
} else {
fmt.Println("key does not exist")
}
fmt.Println(m)
五、map的key
1.map使用哈希表,必须可以比较相等
2.除了slice,map,function的内建类型都可以作为key
3.Struct类型不包含上述字段,可以作为key
六、map使用示例
寻找最长不含有重复字符的字串
1.lastOccurred[x]不存在,或者<start,则无需操作
2.lastOccurred[x] >= start,则更新start
3.更新lastOccurred[x],更新maxLength
func lenthOfNonRepeatingSubStr(s string) int{
lastOccurred := make(map[byte]int)
start := 0
maxLength :=0
for i, ch := range []byte(s){
if lastIndex, ok := lastOccurred[ch]; ok && lastIndex >= start {
start = lastOccurred[ch] + 1
}
if i - start + 1 > maxLength {
maxLength = i - start + 1
}
lastOccurred[ch] = i
}
return maxLength
}