dongzhang5006 2016-11-14 18:39
浏览 45
已采纳

在切片中搜索字符串时找不到句柄

Based on this fairly simple code based on the sort package. The response index of o1 is invalid as pointed by @JimB because a bigger or equals operator is required for binary search

l := []string{"o1", "o2", "o3"} 

i1 := sort.Search(len(l), func(i int) bool { return strings.EqualFold(l[i], "o1") })
fmt.Println("o1:", i1) //PRINTS 3 - WRONG

https://play.golang.org/p/nUs-ozTYsY

The working solution is:

l := []string{"o1", "o2", "o3"} 

i1 := sort.Search(len(l), func(i int) bool { return l[i] >= "o1" })
fmt.Println("o1:", i1)

https://play.golang.org/p/WRsijy_xzV

However this still it's important to bare in mind a important last check. The return value is the index to insert x, which means that you can end up with something like:

o1: 0 (index 0)
o2: 1
o3: 2
o777: 0 (Same 0 index!) 

Therefore it's important as pointed by @JimB to check for data[i] == 23 separately.

if i < len(data) && ---> data[i] == x <--- {
    x is present at data[i]
} else {
    ...
}
  • 写回答

1条回答 默认 最新

  • doujiekeyan0622 2016-11-14 18:50
    关注

    A binary search requires a greater than or less than comparison, otherwise it would just be a linear search over the slice. Any comparison greater than the value at the requested index needs to be true, in order for the search method to scan backwards looking for the smallest index.

    See the default implementation of the string search function from the sort package:

    https://golang.org/src/sort/search.go?s=3673:3717#L91

    func SearchStrings(a []string, x string) int {
        return Search(len(a), func(i int) bool { return a[i] >= x })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?