C ++ vector <vector <int>&gt;开头的保留大小</vector <int>

时间:2015-01-22 09:28:55

标签: c++ arrays vector

在c ++我有

vector<vector<int> > table;

如何调整矢量大小以使其有3行4列全部为零?

类似的东西:

0000 0000 0000

这样我以后可以更改

table[1][2] = 50;

我知道我可以使用for循环执行此操作,但还有其他方法吗?

在1维向量中,我可以:

vector<int> myvector(5);
然后我可以输入例如:

myvector[3]=50;

所以,我的问题是如何用二维,甚至多维向量来做到这一点?

谢谢!

4 个答案:

答案 0 :(得分:3)

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

这将创建一个3行和4列全部初始化的向量  到0

答案 1 :(得分:2)

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

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

如果它是“分段”构建的,那么最后一个更具可读性:

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

应该留作不好的笑话。

答案 2 :(得分:1)

您可以使用std :: vector:

中的 resize()
 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));

答案 3 :(得分:0)

不要!你将拥有复杂的代码和垃圾记忆位置。

而是有一个十二个整数的向量,由一个将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;
}