gpt4 book ai didi

go - 将 slice append 到 slice 的 slice

转载 作者:IT王子 更新时间:2023-10-29 02:24:32 31 4
gpt4 key购买 nike

我有数据结构:

type PosList []int

type InvertedIndex struct {
Capacity int
Len int
IndexList []PosList
}

我对 Add 方法有疑问:

func (ii *InvertedIndex) Add(posList PosList, docId int) {
if ii.Len == ii.Capacity {
newIndexList := make([]PosList, ii.Len, (ii.Capacity+1)*2)
for i := 0; i < ii.Len; i++ {
newIndexList[i] = make([]int, len(ii.IndexList[i]))
copy(newIndexList[i], ii.IndexList[i])
}
ii.IndexList = newIndexList
}

ii.IndexList = ii.IndexList[0 : ii.Len+2]
ii.IndexList[docId] = posList
return
}

或者,我尝试这样的事情:

func (ii *InvertedIndex) Add(posList PosList, docId int) {

if ii.Len == ii.Capacity {
newIndexList := make([]PosList, ii.Len, (ii.Capacity+1)*2)
copy(newIndexList, ii.IndexList)
ii.IndexList = newIndexList
}

ii.IndexList = ii.IndexList[0 : ii.Len+2]
ii.IndexList[docId] = posList
return
}

它们都不起作用,也许有人可以解释我如何将 slice append 到这样的结构中。

最佳答案

你的问题令人困惑。我假设您正在尝试创建一个典型的倒排索引。在这种情况下,您可能想做这样的事情:

package main

import "fmt"

type DocId int

type Positions []int

type docIndex struct {
docId DocId
positions Positions
}

type InvertedIndex struct {
docIndexes []docIndex
}

func New() *InvertedIndex {
return &InvertedIndex{}
}

func (ii *InvertedIndex) Add(docId DocId, positions Positions) {
for i, di := range (*ii).docIndexes {
if di.docId == docId {
di.positions = append(di.positions, positions...)
(*ii).docIndexes[i] = di
return
}
}
di := docIndex{
docId: docId,
positions: positions,
}
(*ii).docIndexes = append((*ii).docIndexes, di)
}

func main() {
ii := New()
docId := DocId(11)
positions := Positions{42, 7}
ii.Add(docId, positions)
positions = Positions{21, 4}
ii.Add(docId, positions)
docId = DocId(22)
positions = Positions{84, 14}
ii.Add(docId, positions)
fmt.Printf("%+v\n", *ii)
}

输出:

{docIndexes:[{docId:11 positions:[42 7 21 4]} {docId:22 positions:[84 14]}]}

声明:

di.positions = append(di.positions, positions...)

将 slice append 到 slice 。


引用资料:

Appending to and copying slices

Arrays, slices (and strings): The mechanics of 'append'

inverted index

关于go - 将 slice append 到 slice 的 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22730754/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com