0

I have a structure with the following form:

struct Grid {
  int nPoints_;
  std::vector<std::vector<double> > pointList_;
}

During the excussion of the program I will read from a file the number of points and pass it to the variable nPoints_.

I would like to know the best procedure for defining the size of the vector.

After knowing the number of points I need to define the size of my vector to be equal to the number of points.

What is the most efficient way of doing this?

Should I:

  Grid.pointList_.resize( Grid.nPoints_);

or

  Grid.pointList_.reserve( Grid.nPoints_);

Afterwards, I will be reading values from a file and storing them in the vector.

Best Regards

Manuel Oliveira
  • 515
  • 4
  • 16
  • 1
    forget about efficiency and "best" unless you know what you actually want to do. Do you want to resize or change capacity? – 463035818_is_not_a_number May 08 '21 at 22:09
  • If you know the end size then those are equivalent and the only difference is how you assign/add the items to the vector. – Retired Ninja May 08 '21 at 22:10
  • I'd prefer the `reserve` way. If you have class types, you have default construction + assignment with `resize`, which can be expensive in some cases. I'd stay with this pattern for double, too, for consistency mainly. – Aconcagua May 08 '21 at 22:46

0 Answers0