4

I am using a vector of pointers to create a data structure and find that I am getting an error that seems unclear. Here is the basic code from the header file

#include <vector>  
using namespace std;  
template <typename Key, typename Value>  
class ST{  
    class STNode{  
    public:  
        STNode(Key k, Value v) : key(k), value(v){}  
        ~STNode(){}  
        Key key;  
        Value value;  
    };  
typedef typename ST<Key, Value>::STNode Node;  
public:  
    ST():v(NULL) {v = new vector<Node*>();}  
    ~ST(){  
        // vector contains allocated objects  
        for(vector<Node*>::iterator it = v->begin(); it != v->end(); ++it)  
        delete (*it);  
        delete v;  
    }  
private:  
    vector<Node*>* v;  
};  

The error message I am receiving on g++ version 4.6.6 is

ST.h: In destructor 'ST<Key, Value>::~ST()':  
ST.h:20: error: expected ';' before 'it'  
ST.h:20: error 'it' was not declared in this scope  

I have tried removing the for loop and simply attempted to declare the iterator and get the scope error. My searches have shown that usually this is attributed to a missed semicolon at the end of the inner class or the lack of public being in the inner class, but this is not the case. Is there a special declaration necessary for an iterator of a vector of pointers?

billz
  • 44,644
  • 9
  • 83
  • 100
  • 2
    A member pointer to container is rarely useful. Consider making the member `vector v;` instead of `vector* v;`. – aschepler Dec 15 '12 at 23:45
  • 1
    @aschepler And more important: it's error-prone... Most people forget that an object can be copied... (Rule of Three) – leemes Dec 15 '12 at 23:51

2 Answers2

2

You are suffering from an interesting quirk of the C++ language. You need to add a typename to you declaration of the iterator (typename vector<Node*>::iterator it). More infomation can be found in the question Why do I need to use typedef typename in g++ but not VS?

Community
  • 1
  • 1
Peter Ogden
  • 710
  • 5
  • 10
  • This worked perfectly. I assumed the typename in the typedef would be sufficient. Informative link btw. Thanks. – physicsguru Dec 15 '12 at 23:52
1

You need to add typedef for vector<Node*>::iterator as it is a dependent name which depends on template a template parameter.

for(typename vector<Node*>::iterator it = v->begin(); it != v->end(); ++it) 
billz
  • 44,644
  • 9
  • 83
  • 100