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 })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多