tags:

views:

132

answers:

3

Hi all,

I am unable to detect the error in the following C++ program. The code defines a Graph class.

#include <vector>
#include <list>

using namespace std;


class Neighbor {
  public:
 int node_id;
 float edge_cost;
 float price;
 Neighbor(int&,float&,float&);
};

Neighbor::Neighbor(int& node_id, float& edge_cost,float& price) {
  this->node_id = node_id;
  this->edge_cost = edge_cost;
  this->price = price;
}

template <class NS>
class Graph {
  private:
 vector<list<NS> > adjacency_list;
 vector<list<NS> >::iterator node_iterator;
  public:
 void add(int node_id, Neighbor& neighbor);
 void remove(int node_id, Neighbor& neighbor);
 Graph();
};


template <class NS>
Graph<NS>::Graph() {
  node_iterator = adjacency_list.begin();
}

template <class NS>
void Graph<NS>::add(int node_id, Neighbor& neighbor) {
if(adjacency_list.size()<node_id){
 while(adjacency_list.size()<node_id)
  adjacency_list.pushback(list<NS>());
}
adjacency_list[node_id].push_back(neighbor);
}

template <class NS>
void Graph<NS>::remove(int node_id,Neighbor& neighbor) {
if(adjacency_list.size()<node_id)
 return;
adjacency_list[node_id].remove(neighbor);
}

When I compile it, I get the following error:

max_flow.cpp:21: error: type ‘std::vector >, std::allocator > > >’ is not derived from type ‘Graph’ max_flow.cpp:21: error: expected ‘;’ before ‘node_iterator’ max_flow.cpp: In constructor ‘Graph::Graph()’: max_flow.cpp:31: error: ‘node_iterator’ was not declared in this scope

vector::iterator works. But why doesn't vector >::iterator ?

Thanks!

+3  A: 

Try using typename:

    typename vector<list<NS> >::iterator node_iterator;

Here is a good reference that explains typename.

Greg Hewgill
A: 

Maybe try typedef your vector. Its usually good practice to make typedefs of types you use.

typedef vector<list<NS> > node;

and then

node::iterator
qba
+2  A: 

Try to replace the line of code from

vector<list<NS> >::iterator node_iterator;

to

typename vector<list<NS> >::iterator node_iterator;

You also need to implement copy-constructor for Neighbor class if you are going to use it as template argument for Graph. This is because you define Neighbor constructor manually and this disables compiler generated copy constructor.

Also you need to define Neighbor::operator== because you use vector::remove method in graph, which requires operator== of its item class.

Actually to check all compilation errors you can use explicit instantiation for the templates:

template class Graph<Neighbor>;

And one more smaaaaaaall error is the following line

adjacency_list.pushback(list<NS>());

should be replaced by

adjacency_list.push_back(list<NS>());
sergdev