Pier
Pier

Reputation: 3

initialize a vector in a class passing its size as argument

I want to initialize a 2D vector ( private in a class) with a size 3xNmax, with Nmax to be assigned in the main (outside the class).

Actually I have:

class Particle
{
public:
   Particle();

   void setNmax(float Nmax){
     _Nmax=Nmax; // this method is actually useless: _Nmax is set below
   }

private:

   int _Nmax=30000; // The parameter I want to set from outside

   vector<vector<float> > _x{3, vector<float> (_Nmax)}; //the 2D vector to be initialized

Do I need to move the declaration and initialization in the constructor?

EDIT1: Thank you for you answers. Concerning the fact that i do not need to use the variable _Nmax, (since the vectors carry with him its own size), i thought that declaring the vector with a certain fixed size (Nmax) at the beginning and avoiding to resize it during the code execution would make my code running faster instead of using many times "push_back" Is this assumption correct?

Upvotes: 0

Views: 611

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69864

#include <vector>

class Particle
{
public:
   Particle(std::size_t nmax = 30000)
     : _Nmax(nmax)
     , _x { std::vector<float>(nmax),
            std::vector<float>(nmax),
            std::vector<float>(nmax)
          }
  {
  }


   void setNmax(std::size_t Nmax)
   {
     _Nmax = Nmax;
     for (auto& e : _x) {
       e.resize(Nmax);
     }
   }

private:

   std::size_t _Nmax=30000; // The parameter I want to set from outside

   std::vector<std::vector<float> > _x; //the 2D vector to be initialized
};

Upvotes: 1

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

Use the member initialization list:

#include <vector>
class Particle
{
    public:
       Particle(size_t Nmax = 30000) : xVect(3, std::vector<float>(Nmax)) {}

    private:
       vector<vector<float> > xVect;
};

Also, there is no need to carry around an extraneous member variable _nMax to denote the number of elements in a vector. A vector knows its own size by calling the vector::size() function.

Introducing extra variables to do this work increases the chances of bugs occurring due to things like forgetting to update this variable if the vector changes size.

Also, it isn't a good idea to start your variable with underscores. Names with underscores are reserved for the system library code.

Upvotes: 1

Related Questions