如何在 C++ 中声明和初始化一个 2d int 向量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2733816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I declare and initialize a 2d int vector in C++?
提问by FrankTheTank
I'm trying to do something like:
我正在尝试执行以下操作:
#include <iostream>
#include <vector>
#include <ctime>
class Clickomania
{
public:
Clickomania();
std::vector<std::vector<int> > board;
};
Clickomania::Clickomania()
: board(12, std::vector<int>(8,0)) <<<<<<<
{
srand((unsigned)time(0));
for(int i = 0; i < 12; i++)
{
for(int j = 0; j < 8; j++)
{
int color = (rand() % 6) + 1;
board[i][j] = color;
}
}
}
However, apparently I can't initialize the "board" vector of vectors this way.
但是,显然我无法以这种方式初始化向量的“板”向量。
How can I create a public member of a 2d vector type and initialize it properly?
如何创建二维向量类型的公共成员并正确初始化它?
采纳答案by Jonathan M Davis
Compiling your code with g++, the error I get is that neither srand()
nor rand()
were declared. I had to add #include <cstdlib>
for the code to compile. But once I did that, it worked just fine. So, I'd say that other than adding that include statement, your code is fine. You're initializing the vector correctly.
用 g++ 编译你的代码,我得到的错误是既srand()
没有rand()
声明也没有声明。我必须添加#include <cstdlib>
代码才能编译。但是一旦我这样做了,它就工作得很好。所以,我想说除了添加包含语句之外,您的代码还可以。您正在正确初始化向量。
Perhaps the code you have doesn't quite match what you posted? I would assume that if your actual code didn't include cstdlib, that you would have quickly understood that that was the problem rather than something with vector. So, if your code doesn't quite match what you posted, maybe that's the problem. If not, what compiler are you using?
也许您拥有的代码与您发布的代码不太匹配?我会假设,如果您的实际代码不包含 cstdlib,那么您很快就会明白这是问题所在,而不是向量的问题。因此,如果您的代码与您发布的内容不完全匹配,那么这可能就是问题所在。如果没有,您使用的是什么编译器?
回答by sanimalp
you should use the constructor that allows you to specify size and initial value for both vectors which may make it a bit easier altogether.
您应该使用允许您为两个向量指定大小和初始值的构造函数,这可能会使它更容易一些。
something like:
就像是:
vector<vector<int>> v2DVector(3, vector<int>(2,0));
should work.
应该管用。
回答by Eddy Pronk
Use a matrix instead:
改用矩阵:
(Basic example from boost documentation)
(来自boost文档的基本示例)
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main () {
using namespace boost::numeric::ublas;
matrix<double> m (3, 3);
for (unsigned i = 0; i < m.size1 (); ++ i)
for (unsigned j = 0; j < m.size2 (); ++ j)
m (i, j) = 3 * i + j;
std::cout << m << std::endl;
}