打印时 C++ 中的 2D 矢量问题 [英] Problem with 2D vector in c++ when printing

查看:26
本文介绍了打印时 C++ 中的 2D 矢量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Vertex {
    public:
    int dist, num;
    vector<Vertex*> edges;
    Vertex() {}
    Vertex(int num) : num(num) {}
};
class K {
public:
    void updateMatrix(vector<vector<int>>& matrix) {
        vector<vector<Vertex>> vec;
        for (vector<int> in : matrix) { 
            vector<Vertex> neu;
            vec.push_back(neu);
            for (int i : in) {
                Vertex k(i);
                cout << k.num;
                neu.push_back(k);
            }
        }
        for (vector<Vertex> in : vec) {
            for (Vertex i : in) cout << i.num << " ";
            cout << endl;
        }
    }
};

当我使用有效的 2D 矢量调用函数时,当我尝试打印 vec 时,输出只有 3 个空行.我该如何解决这个问题?

When I call the function with a valid 2D vector, when I try to print vec the output is just 3 blank lines. How can I fix this?

推荐答案

vec.push_back(neu); 放入(空)变量 副本neuvec.在此之后对 neu 的更改不会影响副本.

vec.push_back(neu); puts a copy of the (empty) variable neu into vec. Changes to neu after this don't affect the copy.

你应该把它移到内循环之后.

You should move that to after the inner loop.

这篇关于打印时 C++ 中的 2D 矢量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆