【发布时间】:2021-12-20 02:51:31
【问题描述】:
我知道发生这种情况的原因,但不知道如何解决,因为我是 STL 新手。
我从用户那里获取输入并使用向量表示加权图。
我声明了一个向量对
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n,m,c;
cout<<"Enter n,m : "<<endl;
cin>>n>>m;
vector<pair<int,int>> adj[n+1];
cout<<"If un-directed input 1 else input 0: "<<endl;
cin>>c;
cout<<"Enter the values of u,v and the waight : "<<endl;
for(int i=0;i<m;i++)
{
int u,v,w;
cin>>u>>v>>w;
adj[u].push_back({v,w});
if(c==1)
adj[v].push_back({u,w});
}
for(int i=0;i<=n;i++)
{
for(int j:adj[i])
{
cout<<i<<"->" << j <<endl;
}
cout<<endl;
}
cout<<"Inserted Successfully";
return 0;
}
但是当我打印这些值时,我无法编译程序。就是因为这个for循环。
for(int j:adj[i])
{
cout<<i<<"->" << j <<endl;
}
由于 adj[i] 中的值是一对边和权重,因此 for_each 循环无法将对值转换为单个 int 值。这可能是原因,但我无法解决这个问题,因为我是 STL 的新手。
请帮忙。
【问题讨论】:
-
这是因为
adj不是整数数组/向量。这是std::pair<int,int>的数组,因此存在无法解决的类型不匹配 -
你为什么要创建一个原始向量数组?我不明白。
-
我正在创建一个向量数组,因为我想在 adj[i] 中跟踪边缘的第一端,而带有权重的边缘的第二端将使用 push_back 存储在向量中()。
-
vector<pair<int,int>> adj[n+1];不是有效的 C++。请参阅Why aren't variable-length arrays part of the C++ standard? 不要使用所谓的“竞赛”或“在线裁判”网站作为学习或教学资源。像这样使用它们可能是有害的。 -
“我无法编译程序。” -- 请提供错误信息(在问题中)。
标签: c++ data-structures stl