通过引用传递时访问std :: vector的元素

时间:2018-07-28 22:11:22

标签: c++ vector pass-by-reference

通过引用传递矢量的元素时,是否有更简单的方法来访问它?这将起作用,但似乎过于复杂。感谢您的提前帮助!

#include <iostream>
#include <vector>
using namespace std;

void my_func(std::vector<int> * vect){
    // this will not work
    cout << *vect[2] << endl;
    // this will work
    cout << *(vect->begin()+2) << endl;
}

int main(){
    std::vector<int> vect = {1,3,4,56};
    my_func(&vect) ;
    return 0;
}

1 个答案:

答案 0 :(得分:4)

在您的示例中,您正在向向量传递 pointer

要通过引用传递,请执行以下操作:

package geojson

//https://stackoverflow.com/questions/15719532/suitable-struct-type-for-unmarshal-of-geojson

import (
    "encoding/json"
)

type Point struct {
    Coordinates []float64
}

type Line struct {
    Points [][]float64
}

type Polygon struct {
    Lines [][][]float64
}

type Geojson struct {
    Type        string          `json:"type"`
    Coordinates json.RawMessage `json:"coordinates"`
    Point       Point           `json:"-"`
    Line        Line            `json:"-"`
    Polygon     Polygon         `json:"-"`
}

func (g *Geojson) UnmarshalJSON(b []byte) error {

    type Alias Geojson
    aux := (*Alias)(g)

    err := json.Unmarshal(b, &aux)

    if err != nil {
        return err
    }

    switch g.Type {
    case "Point":
        err = json.Unmarshal(g.Coordinates, &g.Point.Coordinates)
    case "LineString":
        err = json.Unmarshal(g.Coordinates, &g.Line.Points)
    case "Polygon":
        err = json.Unmarshal(g.Coordinates, &g.Polygon.Lines)
    }

    g.Coordinates = []byte(nil)

    return err
}

func (g Geojson) MarshalJSON() ([]byte, error) {

    var raw json.RawMessage
    var err error

    switch g.Type {
    case "Point":
        raw, err = json.Marshal(&g.Point.Coordinates)
    case "LineString":
        raw, err = json.Marshal(&g.Line.Points)
    case "Polygon":
        raw, err = json.Marshal(&g.Polygon.Lines)
    }

    if err != nil {
        return nil, err
    }

    g.Coordinates = raw

    type Alias Geojson
    aux := (*Alias)(&g)
    return json.Marshal(aux)
}

然后就像访问void my_func(std::vector<int>& vect) ... 一样简单。

通常,当您通过引用传递容器时,您还希望指定vect[index],以免意外修改其中的内容。当然,除非您有意要。