dimanche 26 mai 2019

C++ How to add vector in a vector? vector.push_back( vector<> )?

I'm creating a 2d vector array of char as a class variable, but I'm having troubles of adding a vector into the vector< vector > array.

I'm running gcc with C++ 11 standard.

I tried using vector< vector<char> > row(size, vector<char> ); but errors will show saying I did not define size and vector<char>. If I define it with int size and vector<char> col it will think it's a new function declaration since I'm putting it as a class variable.

So I use the usual method vector< vector<char> > row; and have a function to add another vector into it. So I use this->row[i].push_back( vector<char> col); but then an error saying error: expected primary-expression before ‘col’ appears. I also tried to use just this->row[i].push_back( vector<char> ); but the error is still there saying error: expected primary-expression before ‘)’. This might be dumb but I have no idea how to add a vector into a vector.

class Vector2d {
private:
  int size;
  vector< vector<char> > row;
public:
  void make2d();
};

void Vector2d::make2d() {
  for (int i = 0; i < this->size; i++) {
    this->row[i].push_back( vector<char> col );  // compile error here
    for (int j = 0; j < this->size; j++) {
      this->row[i][j];
    }
  }
  cout << "It works!" << endl;
}

I expect it to add the vector array into the vector array, and that I can use row[i][j] for the rest of the program. But it gives a compiler error saying error: expected primary-expression before ‘col’ I have no idea what to do.

Aucun commentaire:

Enregistrer un commentaire