亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在附加到切片時排序?

在附加到切片時排序?

Go
POPMUISE 2023-06-05 17:12:42
我有一個[]byte我需要按升序排序。我得到一個包含項目的對象,然后迭代數組以創建返回的對象:// unfortunately, for some obscure reason I can't change the data types of the caller and the object from the function call are different, although both are []byte underneath (...)type ID []byte// in another package:type ByteInterface []bytefunc (c *Store) GetAll() ByteInterface {  returnObj := make([]ByteInterface,0)  obj, err := GetData()  // err handling  for _, b := range obj.IDs {     returnObj = append(returnObj, ByteInterface(b))  }  return returnObj}所以我問自己是否有可能立即進行排序,或者我是否需要預先排序append(或事后排序)。returnObjobj.ByteDatareturnOjb
查看完整描述

1 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

在每次迭代中,執行以下操作:


增長目標切片(可能重新分配它):


numElems := len(returnObj)

returnObj = append(returnObj, make([]byte, len(obj))...)

使用標準的插入方法通過找到一個位置來逐個放置源切片中的每個字節來保持目標排序:


for _, b := range obj {

  i := sort.Search(numElems, func (i int) bool {

    return returnObj[i] >= b

  }

  if i < numElems {

    copy(returnObj[i+1:], returnObj[i:])

  }

  returnObj[i] = b

  numElems++

}

(copy應該通過減少復制來優化對的調用,但這留給讀者作為練習。)


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號