C ++矢量<矢量<&INT GT; >在开始储备规模 [英] C++ vector<vector<int> > reserve size at beginning

查看:144
本文介绍了C ++矢量<矢量<&INT GT; >在开始储备规模的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中我有

vector<vector<int> > table;

如何调整向量,它有3行4列,全部为零?

How can I resize vector so that it has 3 rows and 4 columns, all zeros?

类似的东西:

0000
0000
0000

0000 0000 0000

所以,我以后可以例如更改

So that I could later change for example

table[1][2] = 50;

我知道我可以循环做到这一点,但有没有其他办法?

I know i can do this with for loop, but is there other way?

在1维向量我可以有:

vector<int> myvector(5);

,我可以再键入例如:

And i could then type for example:

myvector[3]=50;

所以,我的问题是如何与二维,甚至多维向量做呢?

So, my question is how to do it with 2 dimensional, or even multidimensional vector?

谢谢!

推荐答案

您可以明确的默认值传递给构造函数:

You can pass an explicit default value to the constructor:

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

如果它的建成最后一个是更具可读性分段:

The last one is more readable if it's built "piecewise":

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

特别是如果你使用明确的的std :: - code,看起来像

particularly if you use explicit std:: - code that looks like

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

应预留糟糕的笑话。

should be reserved for bad jokes.

这篇关于C ++矢量&lt;矢量&lt;&INT GT; &GT;在开始储备规模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆