将切片附加到切片切片

时间:2014-03-29 11:54:08

标签: go append slice

我有数据结构:

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
}

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

2 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解你在做什么,但是这样的事情应该可以正常工作,用slice取代map

type PosList []int

type InvertedIndex struct {
    Len       int
    IndexList map[int]PosList
}
func (ii *InvertedIndex) Add(posList PosList, docId int) {
    if ii.IndexList == nil {
        ii.IndexList = make(map[int]PosList)
    }
    if _, ok := ii.IndexList[docId]; ok {
        ii.IndexList[docId] = append(ii.IndexList[docId], posList...)
    } else {
        ii.IndexList[docId] = posList
    }

    ii.Len = len(ii.IndexList)
}

答案 1 :(得分:0)

你的疑问令人困惑。我假设您正在尝试创建典型的倒排索引。在这种情况下,您可能希望执行以下操作:

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...)

将切片附加到切片。


参考文献:

Appending to and copying slices

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

inverted index