# go 用slice模拟vector功能

sydnash · · 3196 次点击 · · 开始浏览

# appendVector

``a = append(a, b...)``

# copy

``b = append([]T(nil), a...)``
``````b = make([]T, len(a))
copy(b, a)``````

# cut删除一段范围i~j

``````copy(a[i:], a[j:])
for k, n := len(a) - j + i, len(a); k < n; k++ {
a[k] = nil //or the zero value of T
}
a = a[:len(a) - j + i]``````

# delete删除指定i

``````copy(a[i:], a[i+1:]
a[len(a] - 1] = nil //or zero value of T
a = a[:len(a)-1]``````

# expand 在i位置扩展j个位置出来

``a = append(a[:i], append(make([]T, j), a[i:]...)...)``

# extend 在最后扩展j个位置

``a = append(a, make([]T, j)...)``

# insert 在i位置插入

``a = append(a[:i], append([]T{x}, a[i:]...)...)``

``````a = append(a, nil)//or zero value of T
copy(a[i+1:], a[i:])
a[i] = x``````

# insertVector 插入vector b

``a = append(a[:i], append(b, a[i:]...)...)``

# pop

``x, a = a[len(a)-1], a[:len(a)-1]``

# push

``a = append(a, x)``

# shift

``x, a := a[0], a[i:]``

# unshift

``a = append([]T{x}, a...)``

# filter

``````b := a[:0]
for _, x := range a {
if f(x) {
b = append(b, x)
}
}``````

# reversing

``````for left, right := 0, len(a) - 1; left < right; left, right = left - 1, right - 1 {
a[left], a[right] = a[right], a[left]
}``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

# appendVector

``a = append(a, b...)``

# copy

``b = append([]T(nil), a...)``
``````b = make([]T, len(a))
copy(b, a)``````

# cut删除一段范围i~j

``````copy(a[i:], a[j:])
for k, n := len(a) - j + i, len(a); k < n; k++ {
a[k] = nil //or the zero value of T
}
a = a[:len(a) - j + i]``````

# delete删除指定i

``````copy(a[i:], a[i+1:]
a[len(a] - 1] = nil //or zero value of T
a = a[:len(a)-1]``````

# expand 在i位置扩展j个位置出来

``a = append(a[:i], append(make([]T, j), a[i:]...)...)``

# extend 在最后扩展j个位置

``a = append(a, make([]T, j)...)``

# insert 在i位置插入

``a = append(a[:i], append([]T{x}, a[i:]...)...)``

``````a = append(a, nil)//or zero value of T
copy(a[i+1:], a[i:])
a[i] = x``````

# insertVector 插入vector b

``a = append(a[:i], append(b, a[i:]...)...)``

# pop

``x, a = a[len(a)-1], a[:len(a)-1]``

# push

``a = append(a, x)``

# shift

``x, a := a[0], a[i:]``

# unshift

``a = append([]T{x}, a...)``

# filter

``````b := a[:0]
for _, x := range a {
if f(x) {
b = append(b, x)
}
}``````

# reversing

``````for left, right := 0, len(a) - 1; left < right; left, right = left - 1, right - 1 {
a[left], a[right] = a[right], a[left]
}``````