简体   繁体   中英

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

在此处输入图片说明Why this code shows me an error on line 31 for 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;
}

Could you please explain briefly where am I wrong. Also this is my first question, so please dont be harsh on me.

In the expression for (auto x1 : Tree) the variable x1 is an std::vector<int> . It is not easy to get the index that a given x1 has in Tree to print it. The solution is to instead iterate over the range of indices in Tree :

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

Now x1 is an integer type which can be printed. You can access the elements of the vector it designates by using Tree 's operator[] :

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

You'll also want to add white space to your output or you'll just get a series of unformatted numbers. For example, you can add a space between the numbers and end the line after each pair :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM