首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印向量向量

打印向量向量
EN

Stack Overflow用户
提问于 2018-11-14 02:39:33
回答 2查看 1.1K关注 0票数 0

我试图在c++中打印一个二维数组,但我遇到了一个问题。我遵循了在for循环中打印向量vectorName.size()的传统方法。所以我遵循的方式就是这个。

代码语言:javascript
复制
#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;
    }
}

但这是印像这样的东西

代码语言:javascript
复制
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

预期产出

代码语言:javascript
复制
0 1 2 3 4 
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4

如何才能正确地打印出向量?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-14 03:07:23

问题基本上是如何填充向量:

代码语言:javascript
复制
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();
}

不过,由于您希望拥有相同的数据,所以效率更高:

代码语言:javascript
复制
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);
}
票数 3
EN

Stack Overflow用户

发布于 2018-11-14 03:06:50

打印std::vectors的std::vectors的两种简单方法:

代码语言:javascript
复制
#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');
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53292417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档