开发者

Creating 2-dimensional vector in class C++

I need to create a vector of vectors full of int开发者_StackOverflowegers. 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_;

};


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)
{
}


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.


You can't initialize a member in a class declaration unless it's const static, because in C++ no code is being run/generated when you are declaring a class. You'll have to initialize them in your constructor.


You should initialize members in the class constructor, not the declaration. The following doesn't seem to be right in any way:

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

If row and puzzle are functions - the parameters should be types. If they're member variables - initialize them in the class constructor.


You cannot initialize mutable members as a part of class definition itself. Instead do assign it in in the constructor.

// ....
Grid()
{
     row.resize(5,0) ;
     puzzle.resize(9,row) ;
}
private:
   vector<int> row;
   vector<vector<int> > puzzle ;
// ..
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜