如何解决为什么这段代码在第31行显示cout << x1 << x2;
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>
。要获取给定x1
在Tree
中具有的索引以进行打印并不容易。解决方案是改为遍历Tree
中的索引范围:
for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
// ...
}
现在x1
是可以打印的整数类型。您可以使用Tree
的{{1}}访问它指定的向量的元素:
operator[]
您还需要在输出中添加空格,否则您将得到一系列未格式化的数字。例如,您可以在数字之间添加空格,并在每对之后的末尾添加行:
for (std::size_t x1 = 0; x1 < Tree.size(); ++x1)
{
for (auto x2 : Tree[x1])
{
cout << x1 << x2;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。