有效地将切片插入另一个切片

问题描述 投票:1回答:1

在Go中,您可以将切片插入另一个切片like this的中间:

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

然而,正如我所理解的那样,首先将a[i:]附加到b,将其复制到b的末尾(并可能重新分配b,然后将整个切片复制到a,再次可能重新分配它。

这似乎有一个额外的副本和分配到你真正需要的。在C ++中,我会这样做(我的意思是......显然没有使用insert)。

// Reserve enough space in `a` for `a` and `b`.
a.reserve(a.size() + b.size());

// Move the second half of `a` to the end.
std::copy(a.begin() + i, a.end(), a.begin() + i + b.size());

// Copy `b` into the middle.
std::copy(b.begin(), b.end(), a.begin() + i);

在Go中有类似的方法吗?

go slice
1个回答
6
投票

这是一个转换为Go假设一片int:

// Reserve space for the combined length of the slices
c := make([]int, len(a)+len(b))

// Copy the first part of a to the beginning
copy(c, a[:i])

// Copy the last part of a to the end
copy(c[i+len(b):], a[i:])

// Copy b to the middle
copy(c[i:], b)

playground example

要利用a的能力,请执行以下操作:

if cap(a) < len(a)+len(b) {
    // Not enough space, allocate new slice
    c := make([]int, len(a)+len(b))

    // Copy the first part of a to the beginning
    copy(c, a[:i])

    // Copy the last part of a to the end
    copy(c[i+len(b):], a[i:])

    a = c
} else {
    // reslice to combined length
    a = a[:len(a)+len(b)]

    // copy the last part of a to the end
    copy(a[i+len(b):], a[i:])

}
// copy b to the middle
copy(a[i:], b)

playground example

© www.soinside.com 2019 - 2024. All rights reserved.