第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

在附加到切片時(shí)排序?

在附加到切片時(shí)排序?

Go
POPMUISE 2023-06-05 17:12:42
我有一個(gè)[]byte我需要按升序排序。我得到一個(gè)包含項(xiàng)目的對象,然后迭代數(shù)組以創(chuàng)建返回的對象:// 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}所以我問自己是否有可能立即進(jìn)行排序,或者我是否需要預(yù)先排序append(或事后排序)。returnObjobj.ByteDatareturnOjb
查看完整描述

1 回答

?
慕工程0101907

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊

在每次迭代中,執(zhí)行以下操作:


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


numElems := len(returnObj)

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

使用標(biāo)準(zhǔn)的插入方法通過找到一個(gè)位置來逐個(gè)放置源切片中的每個(gè)字節(jié)來保持目標(biāo)排序:


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應(yīng)該通過減少復(fù)制來優(yōu)化對的調(diào)用,但這留給讀者作為練習(xí)。)


查看完整回答
反對 回復(fù) 2023-06-05
  • 1 回答
  • 0 關(guān)注
  • 169 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號