简体   繁体   中英

Creating 2-dimensional vector in class C++

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_;

};

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 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 ;
// ..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM