打印矢量 [英] Print a vector of vectors
本文介绍了打印矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在c ++中打印一个二维数组,但是我遇到了问题.我遵循传统的方法在for循环中打印矢量vectorName.size()
.所以我遵循的方式是这样.
I'm trying to print a bidimensional array in c++ but I have a problem. I followed the traditional way to print a vector vectorName.size()
inside a for loop. So the way that I follow was this.
#include <stdio.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <time.h>
using namespace std;
void impMat(vector < vector <int> >, vector < vector <int> >);
int main () {
vector < vector <int> > A;
vector < vector <int> > B;
vector <int> temp;
for(int j = 0; j < 4; j++){
for(int i = 0; i < 5; i++){
temp.push_back(i);
}
A.push_back(temp);
B.push_back(temp);
}
impMat(A,B);
cout << endl;
return 0;
}
void impMat(vector < vector <int> > A,vector < vector <int> > B)
{
for(int i = 0; i < A.size(); i++){
for(int j = 0; j < A[i].size(); j++){
cout << A[i][j] << " ";
}
cout << endl;
}
cout << endl;
for(int i = 0; i < B.size(); i++){
for(int j = 0; j < B[i].size(); j++){
cout << B[i][j] << " ";
}
cout << endl;
}
}
但这就是这样打印
0 1 2 3 4
0 1 2 3 4 0 1 2 3 4
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
预期输出
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
如何正确打印矢量?
推荐答案
问题基本上是如何填充向量:
The problem basically is how you fill your vectors:
for(int j = 0; j < 4; j++)
{
for(int i = 0; i < 5; i++)
{
temp.push_back(i);
}
A.push_back(temp);
B.push_back(temp);
// now temp yet contains all the values entered, so you produce:
// 0, 1, 2, 3, 4 in first loop run,
// 0, 1, 2, 3, 4 0, 1, 2, 3, 4 in second,
// ...
// most simple fix:
temp.clear();
}
不过,由于您仍然希望拥有相同的数据,因此效率更高:
More efficient, though, as you want to have the same data anyway:
for(int i = 0; i < 5; i++)
{
temp.push_back(i);
}
for(int i = 0; i < 4; i++)
{
A.push_back(temp);
B.push_back(temp);
}
这篇关于打印矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文