How to create a DFS and DFS helper method for a vector of pairs?

Viewed 77

We were tasked by our professor to create a graph implementation for a directed weight graph. I started off by creating a vector that accepts a pair of integers which is the edge and its weight. Now I am trying to find a way to implement DFS for the graph but I was unable to. Here is my code. I am sorry if I did not follow the guidelines since I am new to this.

void Graph::DFSUtil(int v, bool visited[])
{
visited[v] = true;
cout << v << " ";

vector<pair<int,int>> :: iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
    if(!visited[*i->first])
    DFSUtil(*i->first, visited);
}

void Graph::DFS(int v)
{
bool visited[vertices];
for (int i = 0; i < vertices; ++i){
    visited[i] = false;
}

}

I keep getting the error:

invalid type argument of unary '*' (have 'int')

Can somebody please explain what I did wrong?

1 Answers

If you want to access the first value of the pair using iterator you need to replace your code in either of the following ways:

// Using arrow operator    
if(!visited[i->first])
    DFSUtil(i->first, visited);

Or

// Using dot operator
if(!visited[(*i).first])
    DFSUtil((*i).first, visited);

-> (Member access operator) has higher priority over * (Dereference operator). So, when you are calling *i->first, it returns the member value first (which you want), then tries to dereference that value (you don't need that) and as a result you get the above mentioned error.

Related