go - sort.SearchInts 工作异常或者我遗漏了一些东西

标签 go

考虑以下示例:

package main

import (
    "fmt"
    "sort"
)

func main() {
    var n int
    var a sort.IntSlice
    a = append(a, 23)   
    a = append(a, 3)
    a = append(a, 10)
    sort.Sort(a)    
    fmt.Println(a)
    n = sort.SearchInts(a, 1)
    fmt.Println(n)
    n = sort.SearchInts(a, 3)
    fmt.Println(n)
}

http://play.golang.org/p/wo4r43Zghv

结果是:

[3 10 23]
0
0

当第一个元素和不存在的元素都返回 0 作为索引时,我应该如何知道 slice 中是否存在数字?

更新 请注意,索引也可以大于 slice 的长度,因此查找 slice 中是否存在元素的正确方法是:

num := 1
n = sort.SearchInts(a, num) 
if n < len(a) && a[n] == num {
  // found
}

最佳答案

这可能看起来是一个功能上奇怪的特性,但它被记录在案:

For instance, given a slice data sorted in ascending order, the call Search(len(data), func(i int) bool { return data[i] >= 23 }) returns the smallest index i such that data[i] >= 23.

明显的解决方案也记录在案:

If the caller wants to find whether 23 is in the slice, it must test data[i] == 23 separately.

关于go - sort.SearchInts 工作异常或者我遗漏了一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14436751/

相关文章:

go - 是否可以在 Golang 类型断言中使用反射数组类型?

go - 尝试将数据解码到 golang 中的界面

go - 如何制作更好的超时功能

dictionary - Golang 中的嵌套 map

templates - Golang 模板(并将函数传递给模板)

去吧,如果我用仅类型接收器声明一个函数,如何调用它?

html - Golang中的html渲染器,没有第三方导入

arrays - 如何在不定义数组大小的情况下将数组传递给 GO 函数?

go - 通过引用传递数组到采用数组的函数的任何方法吗?

Go:通过管道发送 gob 挂起 - 更新:进程外 http.ResponseWriter 正在阻塞