[英]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) {
}
這樣的東西會澄清你的代碼,有一個填充向量的過程,另一個用於打印向量的過程
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
我不是專家,但我喜歡只有一個向量的向量..類似於:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.