简体   繁体   English

包含引用的对象的向量

[英]vector of objects containing references

Edge 

{
   Vertex& v1;
   Vertex& v2;
   float cost;
public :
   Edge(Vertex& v_1, Vertex& v_2) :
      v1(v_1), v2(v_2)
   {
   }
   // other getter and setter functions 
};

How do I create a vector allEdges ? 如何创建矢量allEdges? I know I'll have to create a default constructors and assignment operators supported by vector but I can already see this is going to create issues because of non-existence of default constructors. 我知道我必须创建一个向量支持的默认构造函数和赋值运算符,但是我已经看到,由于默认构造函数的不存在,这将造成问题。

I have created a default constructor just to get by with the std::vector shouting at me but doesn't seem like the right thing to do. 我已经创建了一个默认的构造函数,只是为了通过std :: vector向我大喊大叫,但似乎做不正确。

Using references as member variable is quite restrictive since they have to be initialized in the initializer list of the constructor. 将引用用作成员变量非常有限制性,因为必须在构造函数的初始化程序列表中对其进行初始化。

However, having a vector of objects that in turn have references as member variables is completely allowable, as can be seen in the example below: 但是,完全允许使用对象向量,而这些对象又将引用作为成员变量,如下面的示例所示:

#include <vector>
#include <iostream>

struct Vertex { 
  std::size_t id;
  Vertex(std::size_t const _id) : id(_id) {}
};

class Edge {
   Vertex& v1;
   Vertex& v2;
   double  cost;
public :
   Edge(Vertex& v_1, Vertex& v_2, double const _c) : v1(v_1), v2(v_2), cost(_c) {}
   Vertex& getv1() const { return v1; }
   Vertex& getv2() const { return v2; }
};

int main() {
    Vertex v1(1), v2(2);
    std::vector<Edge> alledges;
    alledges.push_back(Edge(v1, v2, 1.0));
    for(auto i : alledges) std::cout << i.getv1().id << "->" << i.getv2().id << std::endl;

    return 0;
}

LIVE DEMO 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM