简体   繁体   English

打印向量中的值

[英]Printing the values from vector

I know the reason why this is happening but don't know how to solve this as I am new to STL.我知道发生这种情况的原因,但不知道如何解决这个问题,因为我是 STL 的新手。

I am taking the inputs from the user and representing the weighted graph using vectors.我从用户那里获取输入并使用向量表示加权图。 I declared a vector pair<int,int> to store the value of the edge and the weight.我声明了一个向量 pair<int,int> 来存储边的值和权重。

#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;
}

But when i am printing the values i am not able to compile the program.但是当我打印值时,我无法编译程序。 It is due to this for loop.这是由于这个 for 循环。

for(int j:adj[i])
        {
            cout<<i<<"->" << j <<endl;
        }

As the value in adj[i] is a pair of edge and weight thus ,the for_each loop is unable to convert the pair value to a single int value.由于 adj[i] 中的值是一对边和权重,因此 for_each 循环无法将这对值转换为单个 int 值。 This might be the reason but i am unable to solve this as i am new to the STL.这可能是原因,但我无法解决这个问题,因为我是 STL 的新手。

Please Help.请帮忙。

j is a pair of int in order to access the first/second int you have to use j.first/ j.second j 是一对 int 为了访问第一个/第二个 int 你必须使用 j.first/ j.second

    for(pair<int,int> j:adj[i])
    {
        cout<<i<<"->" << j.second <<endl;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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