我正在研究网格中的C ++打印向量。 在这里,我需要将随机数放在3x * 3y的矢量大小中。然后我必须用一个阵列的二维矩阵打印出来。 我不明白如何用一个数组表示二维矩阵。 另外,我不知道如何打印出多维向量。我必须处理print_vector函数,它以网格形式打印向量。 你能帮我改进下面的代码吗?
int main()
{
populate_vector();
return 0;
}
void populate_vector()
{
int x,y;
cout<<"Enter two Vectors x and y \n->";
cin>> x;
cin>> y;
srand((unsigned)time(NULL));
std::vector<int> xVector((3*x) * (3*y));
for(int i = 0; (i == 3*x && i == 3*y); ++i){
xVector[i] = rand() % 255 + 1;
if(i == 3*x){
cout << "\n";
}
}
print_vector(xVector);
}
void print_vector(vector<int> &x) {
}
答案 0 :(得分:0)
这样的事情会澄清你的代码,有一个载有矢量的程序,另一个载有矢量的程序
int main()
{
int x,y;
std::cout<<"Enter two Vectors x and y \n->";
std::cin>> x;
std::cin>> y;
srand((unsigned)time(NULL));
int xSize = x * 3; // it is important to have the size of the final grid stored
int ySize = y * 3; // for code clarity
std::vector<int> xVector( xSize * ySize);
// iterate all y
for ( y = 0 ; y < ySize; ++y) {
// iterate all x
for ( x = 0 ; x < xSize; ++x) {
// using row major order https://en.wikipedia.org/wiki/Row-_and_column-major_order
xVector[y * xSize + x] = rand() % 255 + 1;
}
}
// when printing you want to run y first
for ( y = 0 ; y < ySize; ++y) {
for ( x = 0 ; x < xSize; ++x) {
// iterate all y
printf("%d ", xVector[y * xSize + x] );
}
printf("\n");
}
}
我想你要注意这个步骤,你可以将x和y位置转换为一个数组维度。很简单,你只需要将y乘以x的大小并添加x即可。
二维就是这样的
1 2 3
4 5 6
将会以类似的方式结束
1 2 3 4 5 6
答案 1 :(得分:0)
我不是专家,但我喜欢只有一个矢量矢量......就像这样:
void print_vector(vector<vector<int>>& m_vec)
{
for(auto itY: m_vec)
{
for(auto itX: itY)
cout << itX << " ";
cout << endl;
}
}
void populate_vector()
{
int x,y;
cout << "Enter Two Vectors x and y \n ->";
cin >> x;
cin >> y;
srand((unsigned)time(NULL));
vector<vector <int>> yVector;
for(auto i = 0; i < y*3; ++i)
{
vector<int> xVector;
for(auto j = 0; j < x*3; ++j)
xVector.push_back(rand()%255+1);
yVector.push_back(xVector);
}
print_vector(yVector);
}
编辑:哦,我以前从未见过这个网站,感谢Saykou ......这里的代码正常运行:disco.exe