当前位置: > > > > 附加到切片时排序?
附加到切片时排序?
来源:stackoverflow
2024-04-22 21:51:37
0浏览
收藏
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天米云就整理分享《附加到切片时排序?》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
我有一个 []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 []byte
func (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 以便立即对 returnobj 进行排序,或者是否需要预先对 obj.bytedata 进行排序(或之后对 returnojb 进行排序)。
解决方案
在每次迭代中,执行以下操作:
-
增加目标切片(可能重新分配它):
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的调用应该通过减少复制来优化,但这留给读者作为练习。)
到这里,我们也就讲完了《附加到切片时排序?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注米云公众号,带你了解更多关于的知识点!
