First of all I'm fairly new to C++ so if this is a beginner coding mistake then I'm sorry.
I'm currently working on a graphing class for a homework I got at school. I'm supposed to be able to store edges in a set, array and linked list. As I have done all of these in a separate classes I'm now trying to make them all work in one through templating. Everything works fine for ie. std::set, but when i use my own linked list implementation it somehow fails - it looks like my iterators get messed up somewhere, and both prefix and postfix operators on them result in the same behavior (in a for loop). I'll also add that I'm not using std::list because I'm supposed to make my own implementation of linked list.
My current implementation of the iterator:
template<typename T>
class Iterator{
public: node<T>* pointer;
public:
Iterator(): pointer(0){}
Iterator(node<T>* _pointer): pointer(_pointer){}
Iterator<T> operator++() { pointer = pointer->next; }
Iterator<T> operator++(int) { pointer = pointer->next; }
bool operator!=(Iterator<T> rval){ return !(pointer == rval.pointer); }
bool operator==(Iterator<T> rval){ return (pointer == rval.pointer); }
node<T>* operator()(){ return pointer; }
T operator*(){ return pointer->data; }
};
Single linked list node:
template <typename T>
struct node{
node(): next(0){}
node(T val): data(val), next(0){}
node(node<T>* _next): data(0), next(_next){}
node(T val, node<T>* _next): data(val), next(_next){}
T data;
node<T>* next;
};
And how my list class implements begin() and end():
typedef Iterator<T> iterator;
iterator begin() { return iterator(new node<T>(b)); }
iterator end() { return iterator(); }
Note that b
points to the first element in the linked list
And finally how I'm accessing the elements (this is in a different class that includes the list):
void tree_recurse_f(int node, std::ofstream* file, int level = 0){
[some output code here]
typename T::iterator it;
for (it = Database[node].first.begin(); it != Database[node].first.end(); ++it){
tree_recurse_f(*it, file, (level+1));
}
}
Database
is an std::map<int,std::pair<>>
and .first
points to the type specified by T
(set, list or vector)
Now to the problems:
- Somehow with the current implementation of the lists'
begin()
, it points to an empty node in the output function (++it, and it++ result in the same thing) - Changing the
begin()
toreturn iterator(b)
seems to remove the error in the for loop, though ++it and it++ both result in the same thing - I've managed to discover these two errors by testing only the list class - if i implement it into the graphing class it enters a never ending loop in the output function (*it always points to 0 and doesn't seem to increase with ++it)
Looks like some strange stuff with the iterator to me (especially the fact that alone it works, but inside the other class it doesn't)
// if someone was curious I'm loosely following the linked list tutorial on http://www.cplusplus.com/articles/Lw6AC542/