0

i declared this custom stl vector to take input of a graph to implement the bellmanford algorithm. But i an not understanding how i can take input of the declared stl vector. The declaration code is given below. I need help for understanding the input procedure of this vector. please guide me in this regard.

#include<bits/stdc++.h>
using namespace std;
struct edge{
    int a, b, cost;
};
vector<edge> e;
int nodes, edges;
int main(){
    cin >> nodes >> edges;
}
  • You mean how to use `std::cin` with your custom `struct edge`? [Here is example](https://stackoverflow.com/a/3312347/4165552). Apart from that, name your types and variables [correctly](https://google.github.io/styleguide/cppguide.html#Naming), don't include `stdc++.h` (it is only used in programming contests to save you some coding time), don't use `using namespace std` blindly. – pptaszni Jul 20 '20 at 08:43
  • @pptaszni thank you very much brother for your reply. But i meant how to use std::cin with my vector i.e. vector e. here the data type is a custom struct edge. – shafayet nur Jul 20 '20 at 11:26

1 Answers1

0

One of the possibilities:

struct Edge{
    int a;
    int b;
    int cost;
};

std::istream& operator>>(std::istream& in, Edge& edge)
{
    in >> edge.a;
    in >> edge.b;
    in >> edge.cost;
    return in;
}

using Graph = std::vector<Edge>;

std::istream& operator>>(std::istream& in, Graph& graph)
{
    for (auto& edge : graph)
    {
        in >> edge;
    }
    return in;
}

TEST(Graph, example)
{
    std::istringstream example_input("1 2 3\n4 5 6\n14 13 12");
    Graph graph(3);  // construct a vector with 3 default-constructed elements
    example_input >> graph;
    for (const auto& edge : graph)
    {
        std::cout << "[" << edge.a << ", " << edge.b << ", " << edge.cost << "]\n";
    }
}

It answers your question, however this solution is quite far from SW development best practices. I would rather design a class Graph with appropriate methods for input parsing (maybe from json, or xml file) and methods for getting the edges, setting the costs, etc.

pptaszni
  • 5,591
  • 5
  • 27
  • 43