Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating 2-dimensional vector in class C++

Tags:

c++

class

vector

I need to create a vector of vectors full of integers. However, I continuously get the errors:

error: expected identifier before numeric constant error: expected ',' or '...' before numeric constant

using namespace std;

class Grid {
  public:

  Grid();

  void display_grid();
  void output_grid();

  private:

  vector<int> row(5, 0);
  vector<vector<int> > puzzle(9, row);
  int rows_;
  int columns_;

};
like image 692
Christian Benincasa Avatar asked Apr 23 '11 00:04

Christian Benincasa


2 Answers

You cannot initialize the member variables at the point where you declare them. Use an initialization list in the constructor for that:

Grid::Grid()
  : row(5,0), puzzle(9, row),
    rows_(5), columns_(9)
{
}
like image 63
Oswald Avatar answered Oct 14 '22 09:10

Oswald


C++ class definitions are limited in that you cannot initialise members in-line where you declare them. It's a shame, but it's being fixed to some extent in C++0x.

Anyway, you can still provide constructor parameters with the ctor-initializer syntax. You may not have seen it before, but:

struct T {
   T() : x(42) {
      // ...
   }

   int x;
};

is how you initialise a member, when you might have previously tried (and failed) with int x = 42;.

So:

class Grid {
  public:

  Grid();

  void display_grid();
  void output_grid();

  private:

  vector<int> row;
  vector<vector<int> > puzzle;
  int rows_;
  int columns_;
};

Grid::Grid()
  : row(5, 0)
  , puzzle(9, row)
{
  // ...
};

Hope that helps.

like image 34
Lightness Races in Orbit Avatar answered Oct 14 '22 09:10

Lightness Races in Orbit