[英]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
;为什么这段代码在第 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;
}
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>
.在
for (auto x1 : Tree)
的表达式中for (auto x1 : Tree)
变量x1
是一个std::vector<int>
。 It is not easy to get the index that a given x1
has in Tree
to print it.获取给定
x1
在Tree
的索引来打印它并不容易。 The solution is to instead iterate over the range of indices in Tree
:解决方案是迭代
Tree
的索引范围:
for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
// ...
}
Now x1
is an integer type which can be printed.现在
x1
是可以打印的整数类型。 You can access the elements of the vector it designates by using Tree
's operator[]
:您可以使用
Tree
的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';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.