0

I'm trying to make a program that print the nodes and the edges from graph and shows the shortest path from declared node to all others. The problem is that the print function I create prints too many Nodes with name 0 and edge with weight 0 and I don't know why. Here is the function to add edge in the nodes and function that should be print the graph correctly.

`

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

void addEdge(vector<vector<pair<int, int>>>& graph, int u, int v, int w)
{
    graph[u].push_back(make_pair(v, w));
    graph[v].push_back(make_pair(u, w));
}

void printGraph(vector<vector<pair<int, int>>> adj, int V)
{
    int v, w;
    for (int u = 0; u < V; u++)
    {
        cout << "Node " << u << " makes an edge with \n";
        for (auto it = adj[u].begin(); it != adj[u].end(); it++)
        {

            v = it->first;
            w = it->second;
            cout << "\tNode " << v << " with edge weight ="
                << w << "\n";
        }
        cout << "\n";
    }
}

int main()
{
    vector<vector<pair<int, int>>> graph(9, vector<pair<int, int>>(9));
    addEdge(graph, 0, 1, 4);
    addEdge(graph, 0, 7, 8);
    printGraph(graph,1);
    return 0;
}

`

I tried to find the similar problem but without success.

chrslg
  • 9,023
  • 5
  • 17
  • 31

1 Answers1

1

Your problem more than likely results from

 int main()
 {
    vector<vector<pair<int, int>>> graph(9, vector<pair<int, int>>(9));
    #...
 }

You are default initializing both vectors to a size of 9 and then only adding two edges instead of 9. This behavior results in the default constructor for std::pair which is known to populate both fields with zeros.

See here

Can you show us the output?

RocketMan
  • 46
  • 1
  • Don't ask questions in your answers. If the original question needs clarification, leave a comment on the question. Then, answer the question when it is completely objectively answerable. Also "this answer" (or the title of the other answer) is better link text than "here". – Wyck Nov 16 '22 at 22:37