簡體   English   中英

如何從類/構造函數實際初始化對象的2D向量

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

到目前為止,最接近回答這個問題的唯一鏈接是: 我如何初始化本身具有非平凡構造函數的對象的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;
}

未經測試的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM