猿问

将切片附加到切片的切片

我有数据结构:


type PosList []int


type InvertedIndex struct {

  Capacity  int

  Len       int

  IndexList []PosList

}

我有添加方法的问题:


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

}

它们都不起作用,可能有人可以解释我如何将切片附加到这样的结构中。


慕斯709654
浏览 162回答 2
2回答

UYOU

我不确定我是否完全理解你在做什么,但是这样的事情应该可以正常工作,用slicea替换map:type PosList []inttype InvertedIndex struct {&nbsp; &nbsp; Len&nbsp; &nbsp; &nbsp; &nbsp;int&nbsp; &nbsp; IndexList map[int]PosList}func (ii *InvertedIndex) Add(posList PosList, docId int) {&nbsp; &nbsp; if ii.IndexList == nil {&nbsp; &nbsp; &nbsp; &nbsp; ii.IndexList = make(map[int]PosList)&nbsp; &nbsp; }&nbsp; &nbsp; if _, ok := ii.IndexList[docId]; ok {&nbsp; &nbsp; &nbsp; &nbsp; ii.IndexList[docId] = append(ii.IndexList[docId], posList...)&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; ii.IndexList[docId] = posList&nbsp; &nbsp; }&nbsp; &nbsp; ii.Len = len(ii.IndexList)}
随时随地看视频慕课网APP

相关分类

Go
我要回答