jeudi 2 février 2017

std::copy does not work correctly

I have two class A and B both have a member like below:

class A {
  ...
  std::vector<std::vector<std::vector<size_t>>> grid;
}

class B {
  ...
  std::vector<std::vector<std::vector<size_t>>> grid;
}

I found when I use std::copy to copy from A::grid to B::grid, it will fail. Here is what I do:

// Here is in B's constructor.
// I initialize B::grid with the same size of A::grid
grid = vector<vector<vector<size_t>>>(GetSetting().grid_cols());
for (int i = 0; i < GetSetting().grid_cols(); i++) {
  grid[i] = vector<vector<size_t>>(GetSetting().grid_rows());
  for (int j = 0; j < GetSetting().grid_rows(); j++) {
    grid[i][j].reserve(a.grid[i][j].size());
  }
}

// Copy from A to B
std::copy(a.grid.begin(), a.grid.end(), std::back_inserter(grid));

But if I remove initialize part, then the std::copy will work fine. What's wrong for the initialize part?

Aucun commentaire:

Enregistrer un commentaire