如何在C 中打印网格向量
How to print a grid vector in C++
我正在网格中的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) {
}
我不是专家,但我喜欢只有一个向量。
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 ...这是有效的代码:http://cpp.sh/3vzg
类似的东西会阐明您的代码,在一个过程中填充了向量,而另一个则打印了向量
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
您可以看到它在这里运行
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 打印网格
- 如何在C 中打印网格向量
- C++,打印网格:太长了
- 在 4x4 网格上打印出C++的移动步骤