简体   繁体   English

如何从类/构造函数实际初始化对象的2D向量

[英]How to actually initialize a 2d vector of objects from a class/constructor

so far, the only link that was close to answering the question was this: How do I initialize a stl vector of objects who themselves have non-trivial constructors? 到目前为止,最接近回答这个问题的唯一链接是: 我如何初始化本身具有非平凡构造函数的对象的stl向量?

However, I attempted to do that and I am still stumped on it. 但是,我尝试这样做,但仍然感到困惑。

The relevant code: 相关代码:

Edge 边缘

// Edge Class
class Edge{
  public:
    // std::string is used to avoid not a name type error
    Edge (std::string, double);
    double get_dist();
    std::string get_color();
    ~Edge();
  private:
    std::string prv_color; // prv_ tags to indicate private
    double prv_distance;
};

Edge::Edge (std::string color, double distance){
  prv_color = color;
  prv_distance = distance;
};

Graph 图形

// Graph Class

class Graph{
  public:
    Graph (double, double);
    double get_dist_range();
    ~Graph();

  private:
    double prv_edge_density; // how many edges connected per node
    double prv_dist_range; // start from 0 to max distance
    std::vector < std::vector <Edge*> > nodes; // the proper set-up of 
};

// Graph constructor
Graph::Graph (double density, double max_distance){
  prv_edge_density = density;
  prv_dist_range = max_distance;
  nodes (50, std::vector <Edge*> (50)); // THIS LINE STUMPS ME MOST
};

As I attempted to initialize a vector of object pointers, I get this error from the following line: 当我尝试初始化对象指针的向量时,我从以下行得到此错误:

nodes (50, std::vector <Edge*> (50)); // Error at this line

error: no match for call to ‘(std::vector<std::vector<Edge*, std::allocator<Edge*> >,
  std::allocator<std::vector<Edge*, std::allocator<Edge*> > > >)
  (int, std::vector<Edge*, std::allocator<Edge*> >)’

I would like advice on this as soon as possible. 我希望尽快对此提出建议。

Note: Assume that I have used .cpp files and .h files to separate the code 注意:假设我已经使用.cpp文件和.h文件来分隔代码

You need to learn about initializer lists 您需要了解初始化器列表

// Graph constructor
Graph::Graph (double density, double max_distance) :
  nodes (50, std::vector <Edge*> (50))
{
  prv_edge_density = density;
  prv_dist_range = max_distance;
}

Untested code. 未经测试的代码。

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

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