簡體   English   中英

有效地將一個切片插入另一個切片

[英]Efficiently inserting a slice into another slice

在Go中,您可以像這樣將一個切片插入另一個切片的中間:

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中有類似的方法嗎?

這是假定一片int的Go語言的譯文:

// 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)

游樂場的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM