在 Go 中,您可以将一个切片插入到另一个切片的中间,如下所示:
a = append(a[:i], append(b, a[i:]...)...)
但是,据我了解,首先通过将b
a[i:]
复制到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 的翻译,假设有一部分 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)
游乐场示例
要利用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)
游乐场示例