Golang 在ints的slice中搜索int类型的元素

Golang 在ints的slice中搜索int类型的元素

在Go语言中,slice比数组更加强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。

Go slice中,你可以借助 SearchInts() 函数在给定的ints slice中搜索一个int类型的元素。这个函数在一个排序的ints片断中搜索给定的元素,如果在给定的片断中存在,则返回该元素的索引。如果给定的元素在片断中不存在(可能是len(s_slice)),那么它返回在片断中插入该元素的索引。指定的片断必须以升序排序。它是在sort包下定义的,所以你必须在你的程序中导入sort包以访问SearchInts函数。

语法

func SearchInts(s_slice []int, i int) int

例1 :

// Go program to illustrate how to search
// an int type element in the slice of ints
package main
  
import (
    "fmt"
    "sort"
)
  
// Main function
func main() {
  
    // Creating and searching an element 
    // in the given slice of ints
    // Using SearchInts function
    res1 := sort.SearchInts([]int{1, 2, 3,
                        4, 5, 6, 7, 8}, 5)
      
    res2 := sort.SearchInts([]int{200, 300, 
                 400, 500, 600, 700}, 400)
  
    // Displaying the results
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2: ", res2)
  
}

输出

Result 1:  4
Result 2:  2

例2 :

// Go program to illustrate how to search an 
// element of int type in the slice of ints
package main
  
import (
    "fmt"
    "sort"
)
  
// Main function
func main() {
  
    // Creating and initializing
    // slice of ints using the 
    // shorthand declaration
    slice_1 := []int{34, 67, 78, 10, 43, 67, 8}
    slice_2 := []int{100, 500, 300, 600, 900, 1000}
  
    var f1, f2, f3 int
    f1 = 67
    f2 = 300
    f3 = 100
  
    // Sorting the given slice of ints
    sort.Ints(slice_1)
    sort.Ints(slice_2)
  
    // Displaying the slices
    fmt.Println("Slice 1: ", slice_1)
    fmt.Println("Slice 2: ", slice_2)
  
    // Searching a int type element 
    // in the given slice using 
    // the SearchInts function
    res1 := sort.SearchInts(slice_1, f1)
    res2 := sort.SearchInts(slice_2, f2)
    res3 := sort.SearchInts(slice_2, f3)
  
    // Displaying the results
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2: ", res2)
    fmt.Println("Result 3: ", res3)
  
}

输出

Slice 1:  [8 10 34 43 67 67 78]
Slice 2:  [100 300 500 600 900 1000]
Result 1:  4
Result 2:  1
Result 3:  0

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程