merosss
merosss

Reputation: 555

Vector of struct with constructor

I have read a little bit about structs and vectors and I have ended up writing the following Node struct:

struct Node{
  float posx;
  float posy;
  int accessibility;

  Node() :
    posx(0.f), posy(0.f), accessibility(0) {}

  Node(float x, float y, int access) :
    posx(x), posy(y), accessibility(access) {}

};

Then in the main I want to create some instances of node and I use:

Node sampleNode(1.f, 1.f, 0);

std::vector<Node> graphNodes(N);

And they work fine, ok. But what if I want to create a vector of dimension N using the second constructor?? Because I've tried a couple of combinations (like std::vector<(Node(1.f, 1.f, 0))>,or (graphNodes(1.f, 1.f, 0))(N), but didn't succeded. Unfortunately I wasn't able to find any similar example elsewhere. Thanks in advance.

Upvotes: 3

Views: 2925

Answers (4)

R Sahu
R Sahu

Reputation: 206567

You can do this:

std::vector<Node> graphNodes(N, sampleNode);

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227390

There's an std::vector constructor with a first parameter for the number of elements and a second for a value to which the elements are set:

std::vector<Node> graphNodes(N, Node(1.0f, 1.0f, 0));

This will create a size N vector full of copies of Node(1.0f, 1.0f, 0).

Note that you can also pass an existing instance of Node:

std::vector<Node> graphNodes(N, sampleNode);

Upvotes: 3

timrau
timrau

Reputation: 23058

You may be looking for

std::vector<Node> graphNodes(N, Node(1.f, 1.f, 0));

Upvotes: 2

Brian Bi
Brian Bi

Reputation: 119069

You can't "forward" the constructor arguments to the vector's constructor. Instead, do this:

std::vector<Node> graphNodes(N, Node(1.f, 1.f, 0));

The second argument to the vector's constructor is copied N times to populate the vector.

Upvotes: 3

Related Questions