Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of struct with constructor

Tags:

c++

struct

vector

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.

like image 865
merosss Avatar asked Nov 25 '25 15:11

merosss


2 Answers

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);
like image 53
juanchopanza Avatar answered Nov 27 '25 06:11

juanchopanza


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.

like image 37
Brian Bi Avatar answered Nov 27 '25 05:11

Brian Bi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!