我试图在c++中打印一个二维数组,但我遇到了一个问题。我遵循了在for循环中打印向量vectorName.size()的传统方法。所以我遵循的方式就是这个。
#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如何才能正确地打印出向量?
发布于 2018-11-14 03:07:23
问题基本上是如何填充向量:
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();
}不过,由于您希望拥有相同的数据,所以效率更高:
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);
}发布于 2018-11-14 03:06:50
打印std::vectors的std::vectors的两种简单方法:
#include <vector>
#include <iostream>
int main()
{
std::vector<std::vector<int>> foo{
{ 0, 1, 2, 3, 4 },
{ 0, 1, 2, 3, 4 },
{ 0, 1, 2, 3, 4 },
{ 0, 1, 2, 3, 4 }
};
// range-based for-loops:
for (auto const &row : foo) {
for (auto const &col : row) {
std::cout << col << ' ';
}
std::cout.put('\n');
}
std::cout.put('\n');
// ordinary for-loops:
for (std::size_t row{}; row < foo.size(); ++row) {
for (std::size_t col{}; col < foo[row].size(); ++col) {
std::cout << foo[row][col] << ' ';
}
std::cout.put('\n');
}
}https://stackoverflow.com/questions/53292417
复制相似问题