简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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