为什么这段代码在第 31 行显示错误 cout<<x1<<x2;

Why this code shows me an error on line 31 for cout<<x1<<x2;

为什么此代码在第 31 行显示 cout<<x1<<x2;

的错误
//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) 中,变量 x1 是一个 std::vector<int>。获取给定 x1Tree 中的索引来打印它并不容易。解决方案是迭代 Tree 中的索引范围:

for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
    // ...
}

现在x1是一个可以打印的整数类型。您可以使用 Treeoperator[] :

访问它指定的向量的元素
for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
    for (auto x2 : Tree[x1])
    {
        cout << x1 << x2;
    }
}

您还需要在输出中添加白色 space,否则您只会得到一系列未格式化的数字。例如,您可以在数字之间添加一个 space 并在每对数字之后结束该行:

for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
    for (auto x2 : Tree[x1])
    {
        cout << x1 << ' ' << x2 << '\n';
    }
}