Golang 切片的其他妙用
        【摘要】 过滤而不分配这个技巧利用了一个切片与原始切片共享相同的支持数组和容量这一事实,因此存储被重新用于过滤后的切片。当然,原始内容是修改过的。b := a[:0]for _, x := range a {	if f(x) {		b = append(b, x)	}}对于必须进行垃圾回收的元素,可以在之后包含以下代码:for i := len(b); i < len(a); i++ {	a[i] =...
    
    
    
    
过滤而不分配
这个技巧利用了一个切片与原始切片共享相同的支持数组和容量这一事实,因此存储被重新用于过滤后的切片。当然,原始内容是修改过的。
b := a[:0]
for _, x := range a {
	if f(x) {
		b = append(b, x)
	}
}
对于必须进行垃圾回收的元素,可以在之后包含以下代码:
for i := len(b); i < len(a); i++ {
	a[i] = nil // or the zero value of T
}
反转
要用相同的元素但以相反的顺序替换切片的内容:
for i := len(a)/2-1; i >= 0; i-- {
	opp := len(a)-1-i
	a[i], a[opp] = a[opp], a[i]
}
同样的事情,除了两个索引:
for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
	a[left], a[right] = a[right], a[left]
}
洗牌
Fisher–Yates 算法:
Since go1.10, this is available at math/rand.Shuffle
for i := len(a) - 1; i > 0; i-- {
    j := rand.Intn(i + 1)
    a[i], a[j] = a[j], a[i]
}
最小分配的批处理
如果你想对大切片进行批处理,这很有用。
actions := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
batchSize := 3
batches := make([][]int, 0, (len(actions) + batchSize - 1) / batchSize)
for batchSize < len(actions) {
    actions, batches = actions[batchSize:], append(batches, actions[0:batchSize:batchSize])
}
batches = append(batches, actions)
产生以下结果:
[[0 1 2] [3 4 5] [6 7 8] [9]]
就地重复数据删除(比较)
import "sort"
in := []int{3,2,1,4,3,2,1,4,1} // any item can be sorted
sort.Ints(in)
j := 0
for i := 1; i < len(in); i++ {
	if in[j] == in[i] {
		continue
	}
	j++
	// preserve the original data
	// in[i], in[j] = in[j], in[i]
	// only set what is required
	in[j] = in[i]
}
result := in[:j+1]
fmt.Println(result) // [1 2 3 4]
如果可能的话,移动到前面,或者如果不存在则放在前面。
// moveToFront moves needle to the front of haystack, in place if possible.
func moveToFront(needle string, haystack []string) []string {
	if len(haystack) != 0 && haystack[0] == needle {
		return haystack
	}
	prev := needle
	for i, elem := range haystack {
		switch {
		case i == 0:
			haystack[0] = needle
			prev = elem
		case elem == needle:
			haystack[i] = prev
			return haystack
		default:
			haystack[i] = prev
			prev = elem
		}
	}
	return append(haystack, prev)
}
haystack := []string{"a", "b", "c", "d", "e"} // [a b c d e]
haystack = moveToFront("c", haystack)         // [c a b d e]
haystack = moveToFront("f", haystack)         // [f c a b d e]
滑动窗口
func slidingWindow(size int, input []int) [][]int {
	// returns the input slice as the first element
	if len(input) <= size {
		return [][]int{input}
	}
	// allocate slice at the precise size we need
	r := make([][]int, 0, len(input)-size+1)
	for i, j := 0, size; j <= len(input); i, j = i+1, j+1 {
		r = append(r, input[i:j])
	}
	return r
}
        
            【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
                cloudbbs@huaweicloud.com
                
            
        
        
        
        
        
        
        - 点赞
 - 收藏
 - 关注作者
 
            
           
评论(0)