当前位置:网站首页>Section 1 array and slicing in Chapter 6
Section 1 array and slicing in Chapter 6
2022-04-23 03:27:00 【Python code doctor】
Array
summary
An array is a collection of data of the same type . Every data contained in an array is called an array element (element), The number of elements in an array is called the length of the array .
Array length must be constant , And it's part of the type . [2]int and [3]int It's different types .
var n int = 10
var a [n]int //err, non-constant array bound n
var b [10]int //ok
Operation array
Each element of the array can be accessed through index subscripts , The index range is the index range from 0 Start To the length of the array minus 1 The location of .
var a [10]int
for i := 0;i < 10; i++ {
a[i] = i + 1
fmt.Printf("a[%d] = %d\n", i, a[i])
}
// range Has two return values , The first return value is the array subscript of the element , The second return value is the value of the element
for i, v :=range a {
fmt.Println("a[", i, "]=",v)
}
Built in functions len( length ) and cap( Capacity ) Both return the length of the array ( Element quantity ):
a := [10]int{
}
fmt.Println(len(a),cap(a)) //10 10
initialization :
a := [3]int{
1, 2} // Uninitialized element value is 0
b := [...]{
1, 2, 3} // Determine the array length by initializing the value
c := [5]int{
2: 100, 4: 200} // Initializing elements with index numbers , Uninitialized element value is 0
// Support multidimensional array
d := [4][2]int{
{
10, 11}, {
20, 21}, {
40, 41}}
e := [...][2]int{
{
10, 11}, {
20, 21}, {
30, 31}, {
40, 41}} // The second dimension can't write "..."
f := [4][2]int{
1: {
20, 21}, 3: {
40, 41}}
g := [4][2]int{
1: {
0: 20}, 3: {
1: 41}}
fmt.Println(d, e, f, g)
You can use... Between arrays of the same type == or != Compare , But you can't use < or >, You can also assign values to each other :
a := [3]int{
1, 2, 3}
b := [3]int{
1, 2, 3}
c := [3]int{
1,2}
fmt.Println(a == b, b == c) //true false
var d [3]int
d = a
fmt.Println(d) //[1 2 3]
Passing arrays between functions
Based on memory and performance , Passing arrays between functions is a costly operation . When passing variables between functions , It's always delivered by value . If this variable is an array , It means the whole array , No matter how long , Will be copied completely , And pass it to the function .
func modify(array [5]int) {
array[0] = 10 // The view modifies the first element of the array
// In modify(), array values: [10 2 3 4 5]
fmt.Println("In modify(), array values:", array)
}
func main() {
array := [5]int{
1, 2, 3 ,4, 5} // Define and initialize an array
modify(array) // Pass it to a function , And try to modify the contents of the array in the function
//In main(), array values: [1 2 3 4 5]
fmt.Println("In main(), array values:", array)
}
Array pointer as function parameter :
func modify(array *[5]int) {
(*array)[0] = 10
// In modify(), array values: [10 2 3 4 5]
fmt.Println("In modify(),array values:", *array)
}
func main() {
array := [5]int{
1, 2, 3, 4, 5} // Define and initialize an array
modify(&array)
// In main(), array values: [10 2 3 4 5]
fmt.Println("In main(), array values:", array)
}
section
summary
The length of the array cannot be modified after it is defined ; Arrays are value types , Each delivery will produce a copy . Obviously, this kind of data structure can not fully meet the real needs of developers .Go The language provides array slicing (slice) To make up for the array .
Slices are not arrays or array pointers , It refers to... Through internal pointers and related properties ⽤ Array ⽚ paragraph , To achieve change ⻓⽅ case .
slice It's not really a dynamic array , It's a reference type .slice Always point to the bottom array,slice The statement can also look like array equally , It just doesn't need length .
Creation and initialization of slices
slice The difference with arrays : When you declare an array , Square brackets indicate the length or use of the array … Calculate the length automatically , The statement slice when , There are no characters in brackets .
var s1 []int // Declaration slices and declarations array equally , Knowledge is short of length , This is empty (nil) section
s2 := []int{
}
// make([]T, length, capacity) //capacity Omit , And length The value of is the same
var s3 [int] = make([]int, 0)
s4 :=make([]int, 0, 0)
s5 := []int{
1, 2, 3} // Create slices and initialize
Be careful :make Can only be created slice、map and channel, And return an initial value ( Nonzero ).
Operation of slicing
Slice off
operation | meaning |
---|---|
s[n] | section s The index position is n The item |
s[:] | From slice s Index position of 0 To len(s)-1 Slices obtained at |
s[low:] | From slice s Index position of low To len(s)-1 Slices obtained at |
s[:high] | From slice s Index position of 0 To high Slices obtained at ,len=high |
s[low:high] | From slice s Index position of low To high Slices obtained at ,len=high-low,cap=max-low |
s[low:high:max] | From slice s Index position of low To high Slices obtained at ,len=high-low,cap=max-low |
len(s) | section s The length of , Always <=cap(s) |
cap(s) | section s The capacity of , Always >=len(s) |
example :
array := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
operation | result | len | cap | explain |
---|---|---|---|---|
array[:6:8] | [0 1 2 3 4 5] | 6 | 8 | Omit low |
array[5:] | [5 6 7 8 9] | 5 | 5 | Omit high、max |
array[:3] | [0 1 2] | 3 | 10 | Omit high、max |
array[:] | [0 1 2 3 4 5 6 7 8 9] | 10 | 10 | Omit all |
Slice and underlying array relationships
s := []int{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s1 := s[2:5] //[2 3 4]
s1[2] = 100 // Modify the slice to change the underlying array
fmt.Println(s1, s) //[2 3 100] [0 1 2 3 100 5 6 7 8 9]
s2 := s1[2:6] // The new slice still points to the original underlying array [100 5 6 7]
s2[3] = 200
fmt.Println(s2) //[100 5 6 200]
fmt.Println(s) //[0 1 2 3 100 5 6 200 8 9]
Built-in functions
append
append Functional direction slice Add data at the end , Return to new slice object :
var s1 []int // establish nil Switch
//s1 := make([]int, 0)
s1 = append(s1, 1) // Additional 1 Elements
s1 = append(s1, 2, 3) // Additional 2 Elements
s1 = append(s1, 4, 5, 6) // Additional 3 Elements
fmt.Println(s1) //[1 2 3 4 5 6]
s2 := make([]int, 5)
s2 = append(s2, 6)
fmt.Println(s2) //[0 0 0 0 0 6]
s3 := []int{
1, 2, 3}
s3 = append(s3, 4, 5)
fmt.Println(s3)//[1 2 3 4 5]
append The function intelligently increases the capacity of the underlying array , Once the capacity of the original underlying array is exceeded , Usually, the 2 Double the capacity to reallocate the underlying array , And copy the original data :
func main() {
s := make([]int, 0, 1)
c := cap(s)
for i := 0; i < 50; i++ {
s = append(s, i)
if n := cap(s); n > c {
fmt.Printf("cap: %d -> %d\n", c, n)
c = n
}
}
/* cap: 1 -> 2 cap: 2 -> 4 cap: 4 -> 8 cap: 8 -> 16 cap: 16 -> 32 cap: 32 -> 64 */
}
copy
function copy In two slice Copy data between , Copy ⻓ Du Yi len Small is the standard. , Two slice Can point to the same ⼀ The underlying array .
data := [...]int{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s1 := data[8:] //{8, 9}
s2 := data[:5] //{0, 1, 2, 3, 4}
copy(s2, s1) // dst:s2, src:s1
fmt.Println(s2) //[8 9 2 3 4]
fmt.Println(data) //[8 9 2 3 4 5 6 7 8 9]
Slice as a function parameter
func test(s []int) {
// Slice as a function parameter
s[0] = -1
fmt.Println("test : ")
for i, v := range s {
fmt.Printf("s[%d]=%d, ", i, v)
//s[0]=-1, s[1]=1, s[2]=2, s[3]=3, s[4]=4, s[5]=5, s[6]=6, s[7]=7, s[8]=8, s[9]=9,
}
fmt.Println("\n")
}
func main() {
slice := []int{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
test(slice)
fmt.Println("main : ")
for i, v := range slice {
fmt.Printf("slice[%d]=%d, ", i, v)
//slice[0]=-1, slice[1]=1, slice[2]=2, slice[3]=3, slice[4]=4, slice[5]=5, slice[6]=6, slice[7]=7, slice[8]=8, slice[9]=9,
}
fmt.Println("\n")
}
版权声明
本文为[Python code doctor]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220619244299.html
边栏推荐
- MySQL keyword group_ Concat, combined connection query
- 2022 团体程序设计天梯赛 模拟赛 L1-7 矩阵列平移 (20 分)
- 批量下載文件----壓縮後再下載
- Codeforces Round #784 (Div. 4)题解 (第一次AK cf (XD
- L3-011 direct attack Huanglong (30 points)
- Initial experience of talent plan learning camp: communication + adhering to the only way to learn open source collaborative courses
- Detailed description of MySQL index [B + tree index, hash index, full-text index, overlay index]
- 一文了解全面静态代码分析
- Utgard connection opcserver reported an error caused by: org jinterop. dcom. common. JIRuntimeException: Access is denied. [0x800
- MySQL query specifies that a row is sorted to the first row
猜你喜欢
超好用的Excel异步导出功能
C set
JS inheritance
C interface
2022 团体程序设计天梯赛 模拟赛 L1-7 矩阵列平移 (20 分)
File upload vulnerability summary and upload labs shooting range documentary
Code forces round # 784 (DIV. 4) solution (First AK CF (XD)
12.<tag-链表和常考点综合>-lt.234-回文链表
2022 group programming ladder simulation l2-1 blind box packaging line (25 points)
Romantic silhouette of L2-3 of 2022 group programming ladder Simulation Competition (25 points)
随机推荐
MySql关键字GROUP_CONCAT,组合连接查询
2022 group programming ladder simulation l2-1 blind box packaging line (25 points)
Generate QR code through zxing
Optimization of especially slow startup in idea debugging mode
超好用的Excel异步导出功能
MySQL之explain关键字详解
ThreadLocal test multithreaded variable instance
集合之List接口
Unity knowledge points (ugui)
JS recursive tree structure calculates the number of leaf nodes of each node and outputs it
Advanced sorting - fast sorting
There is no index in the database table. When inserting data, SQL statements are used to prevent repeated addition (Reprint)
POI create and export Excel based on data
Visual programming -- how to customize the mouse cursor
Batch download of files ---- compressed and then downloaded
Test questions and some space wars
通过 zxing 生成二维码
TCP three handshakes and four waves
2021-08-31
浅学一下I/O流和File类文件操作