C++ vector<vector<int> > 开头保留大小

C++ vector<vector<int> > reserve size at beginning

在 C++ 中我有

vector<vector<int> > table;

如何调整向量的大小,使其具有 3 行和 4 列,全为零?

类似的东西:

0000 0000 0000

这样我以后可以更改例如

table[1][2] = 50;

我知道我可以用 for 循环做到这一点,但还有其他方法吗?

在一维向量中我可以有:

vector<int> myvector(5);

然后我可以输入例如:

myvector[3]=50;

那么,我的问题是如何使用二维甚至多维向量来实现?

谢谢!

您可以使用 resize() 来自 std::vector :

 table.resize(4);                           // resize the columns
 for (auto &row : table) { row.resize(3); } // resize the rows

或者直接初始化为:

std::vector<std::vector<int>> table(4,std::vector<int>(3));
vector<vector<int> > table(3, vector<int>(4,0));

这将创建一个包含 3 行和 4 列的向量,所有这些都已初始化 到 0

您可以将显式默认值传递给构造函数:

vector<string> example(100, "example");  
vector<vector<int>> table (3, vector<int>(4));
vector<vector<vector<int>>> notveryreadable (3, vector<vector<int>>(4, vector<int> (5, 999)));

最后一个如果构建的话可读性更好"piecewise":

vector<int> dimension1(5, 999);
vector<vector<int>> dimension2(4, dimension1);
vector<vector<vector<int>>> dimension3(3, dimension2);

特别是如果你使用显式 std:: - 代码看起来像

std::vector<std::vector<std::vector<std::string>>> lol(3, std::vector<std::vector<std::string>>(4, std::vector<std::string> (5, "lol")));

应该保留给糟糕的笑话。

不要!您将拥有复杂的代码和垃圾内存位置。

取而代之的是一个由 12 个整数组成的向量,由 class 包裹,将 2D 索引转换为 1D 索引。

template<typename T>
struct matrix
{
   matrix(unsigned m, unsigned n)
     : m(m)
     , n(n)
     , vs(m*n)
   {}

   T& operator()(unsigned i, unsigned j)
   {
      return vs[i + m * j];
   }

private:
   unsigned m;
   unsigned n;
   std::vector<T> vs;
};

int main()
{
   matrix<int> m(3, 4);   // <-- there's your initialisation
   m(1, 1) = 3;
}