如何从类/构造函数中初始化对象的2d向量

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

本文关键字:对象 初始化 2d 向量 构造函数      更新时间:2023-10-16

到目前为止,唯一接近回答这个问题的链接是:我如何初始化一个stl向量的对象本身有非平凡的构造函数?

然而,我试着去做,但我仍然被它难住了。

相关代码:

边缘
// 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 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
};

当我试图初始化对象指针的向量时,我从下面的行中得到了这个错误:

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*> >)’

我想尽快得到关于这件事的建议。

注意:假设我使用了。cpp文件和。h文件来分隔代码

你需要了解初始化列表

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

未测试的代码。