【问题标题】:Initialize and allocate size for 2D vector member variable using a member function at run-time在运行时使用成员函数初始化和分配二维向量成员变量的大小
【发布时间】:2016-11-09 13:33:49
【问题描述】:

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

这种方法有问题吗?

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

【问题讨论】:

  • 我会使用 vector&lt;vector&lt;int&gt;&gt;(row, vector&lt;int&gt;(column, DEFAULT_VALUE)).swap(m_matrix); 而不是 std::move。
  • 阿列克谢·巴恩斯:如果我按照显示的方式做会有什么问题吗?
  • 取决于您所说的错误,这是一个主观问题。但是,出于所有意图和目的,您可以使用任何您喜欢的方法来构造和初始化成员。
  • 两种解决方案似乎都能在恒定时间内达到结果。谢谢你的评论

标签: c++ vector constructor runtime 2d


【解决方案1】:

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

您似乎在征求建议,所以我建议vector&lt;vector&lt;int&gt;&gt; 是一个糟糕的选择,因为所有子vectors 的大小都相同。您可以考虑使用单个vector。我寻找了一个使用单个vector 替换vector-of-vectors 的示例,而我在http://stackoverflow.com 上可以找到的最简单的东西是:https://stackoverflow.com/a/37868317/2642059 这里写得更好一点不过:http://upcoder.com/2/efficient-vectors-of-vectors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多