在 运行 时间使用成员函数初始化和分配 2D 向量成员变量的大小

Initialize and allocate size for 2D vector member variable using a member function at run-time

如何在运行时使用成员函数初始化和分配二维向量成员变量的大小?

这种方法有问题吗?

class A {

vector<vector<int>> m_matrix;

// trying to resize without using explicit resize
// using the constructor of 2D vectors at run time
// want the code to look simpler and avoid new/pointers
void initialize_matrix(int row, int column) {
  m_matrix = std::move(vector<vector<int>>(row, vector<int>(column, DEFAULT_VALUE)));
}
}

您的问题的答案是是的,可以正常工作。它使用 move 来防止编译器错误地使用复制赋值,这是一个很好的接触。

你似乎在寻求建议,所以我建议 vector<vector<int>> 是一个糟糕的选择,因为所有子 vector 都是相同的大小。您可以考虑使用单个 vector。我寻找了一个使用单个 vector 替换 vector-of-vector 的示例,这是我在 http://whosebug.com was this: There's a little bit better write up here though: http://upcoder.com/2/efficient-vectors-of-vectors

上找到的最简单的东西