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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测