So as the title suggests, I've made my own template for an iterator which looks like this:
template <class Element>
class IteratorDL {
private:
DoubleNode<Element> *current;
public:
IteratorDL(DoublyList<Element>);
~IteratorDL();
void next();
void back();
bool isValid();
Element getCurrent();
};
template <class Element>
IteratorDL<Element>::IteratorDL(DoublyList<Element> dl) {
current = dl.first;
cout << current->info; //this will return to me the correct value that I'm looking for
}
template <class Element>
Element IteratorDL<Element>::getCurrent() {
if (isValid()) {
COUT << current->info; // this will return to me something like an address, random numbers, I don't know.
return current->info;
}
else {
return 0;
}
}
I've only posted the 2 functions that really trouble me. I'm supposed to use this over a Doubly Linked list (same, custom made). DoubleNode looks like this:
template
class DoubleNode {
private:
Element info;
DoubleNode *next;
DoubleNode *back;
The problem I'm having is that getCurrent() doesn't return what it's supposed to return to me the value contained in the node current but it returns to me something like an address, I can't really tell. I commented the iterator code so you can understand better what happens and I'm pretty new to c++, that's why maybe I don't understand where things go wrong.
I also tried making the linked list as a private part of the iterator but it still didn't solve the problem. After further research, I believe getCurrent() is returning some other part of memory so for some reason, in that certain function, current->info doesn't lead to where it's supposed to?
I tried this approach as well:
private:
DoublyList<Element> dl;
DoubleNode<Element> *current;
But same problem
Edit with code calling the functions:
DoublyList<int> dl;
dl.addFirst(1);
dl.addFirst(2);
dl.addFirst(3);
dl.addFirst(4);
int c;
IteratorDL<int> *it = new IteratorDL<int>(dl);
cout << it->getCurrent(); //this should return 4 but it returns random number
// c = it->getCurrent();
// assert(c == 4);
Edit for the doubly list declaration:
template <class Element>
class DoublyList {
private:
DoubleNode<Element> *first;
DoubleNode<Element> *last;
int count;