c++ - 为什么这段代码在第31行显示cout << x1 << x2;

标签 c++ debugging compiler-errors cout

为什么此代码向我显示cout<<x1<<x2的第31行有错误;

//This code is used to define a tree.
#include <bits/stdc++.h>
#include <algorithm>
#include <functional>
#include <iostream>

using namespace std;

int main()

{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    vector<vector<int>> Tree;
    int edge, n1, n2;  //edges for the tree
    cin >> edge;
    Tree.resize(edge);

    for (int i = 0; i < edge; i++)
    {
        cin >> n1 >> n2;
        Tree[n1].push_back(n2);
    }

    for (auto x1 : Tree)
    {
        for (auto x2 : x1)
        {
            cout << x1 << x2; //Here, it shows error
        }
        cout << endl;
    }

    return 0;
}
您能简要解释一下我哪里错了。这也是我的第一个问题,所以请不要对我严厉。

最佳答案

在表达式for (auto x1 : Tree)中,变量x1std::vector<int>。要获得给定的x1Tree中具有的索引以进行打印,这并不容易。解决方案是改为遍历Tree中的索引范围:

for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
    // ...
}
现在,x1是可以打印的整数类型。您可以使用Treeoperator[]来访问它指定的 vector 的元素:
for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
    for (auto x2 : Tree[x1])
    {
        cout << x1 << x2;
    }
}
您还需要在输出中添加空格,或者只是获得一系列未格式化的数字。例如,您可以在数字之间添加一个空格,并在每对之后的行末尾:
for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
    for (auto x2 : Tree[x1])
    {
        cout << x1 << ' ' << x2 << '\n';
    }
}

关于c++ - 为什么这段代码在第31行显示cout << x1 << x2;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64103951/

相关文章:

c++ - 从文件中删除特定记录(或数据)

c# - 从 C# 调用 C++ exe 函数

c++ - 在 OpenCV 中查找 SparseMat 的最大和最小位置

java - JDB 面临问题 - 未命中断点

visual-studio-2010 - 如何防止 Visual Studio 报告捕获的异常?

c++ - C++ 中带有连续括号的 Emacs 缩进

python - R 记录器的调试器级别 - FINEST 是否等于 Python 的 DEBUG?

c - 为什么我一直得到 "error: variable has incomplete type ' struct intVec'?

c# - 定义自己的关键字和含义

c - 将 C++11 和 C 库一起用于复数