Hello guys.
I am trying to write my first small project with C++ - implement stl list like collection class. This is what i have a the moment:
Code:
#ifndef GUARD_link_list_h
#define GUARD_link_list_h
template <class T>
struct Node {
public:
Node() { link = NULL; }
Node(const Node* l, const T& d) { link = l; data = d; }
T& get_data() { return data; }
void set_data(const T& v) { data = v; }
Node* get_link() { return link; }
void set_link(Node* l) { link = l; }
private:
Node* link;
T data;
};
template <class T>
class Link_list {
public:
typedef T* iterator;
typedef const T* const_iterator;
typedef T value_type;
typedef size_t size_type;
// The Rule of Three
Link_list () { init(); }
virtual ~Link_list () {}
//Link_list& operator=(const Link_list&);
// operators
T* operator++() { return next(); }
// methods to manage the collection
void push_back(const T&);
iterator begin() { return first; }
iterator end() { return last; }
bool empty() { return first == 0; }
private:
Node<T>* node;
iterator first;
iterator last;
// private methods
void init();
T* next();
};
template <class T>
void Link_list<T>::init() {
first = last = 0;
}
template <class T>
void Link_list<T>::push_back(const T& v) {
Node<T> *n = new Node<T>;
n->set_data(v);
n->set_link(node);
node = n;
if(!empty())
last = &(node->get_data());
else
first = last = &(node->get_data());
}
template <class T>
T* Link_list<T>::next() {
node = node.get_link();
return node.get_data();
}
#endif /* end of include guard: GUARD_link_list_h */
I know it's not a very nice code.
The issue I have is with data values. I test it with this code:
Code:
Link_list<int> t;
t.push_back(5);
t.push_back(9);
t.push_back(2);
Link_list<int>::iterator it = t.begin();
std::cout << *it << std::endl;
++it;
std::cout << *it << std::endl;
Link_list<int>::iterator it2 = t.end();
std::cout << *it << std::endl;
The begin() and end() is alright, but the problem is when I try to increment the iterator. The value is 0, while I expect 9.
What did I do wrong here (presumably with pointers)?
Also, some comments on coding style would be nice about bad C++ programming practice you might notice here.