Sign in to follow this  
pubeinsoap

linked list iterator in c++

Recommended Posts

A question in my book asks me to write a bidirectional iterator for my node class. i am having trouble trying to work out exactly how to implement this. does this mean write a function that takes an iterator? heres my code so far: #include <list> #include <string> #include <iostream> #include <fstream> using std::list; using std::string; using std::cout; using std::endl; using std::ifstream; #include "split.h" class node{ public: int x; string d; node* next; node* prev; }; int main() { ifstream in("a.txt"); string s; list<string> d; while(getline(in, s)) { list<string> a = split(s); for(list<string>::iterator i = a.begin(); i != a.end(); ++i) { d.push_back(*i); } } node *root; node *cdt; root = new node; root->next = 0; root->prev = 0; root->x = 1; cdt = root; if ( cdt != 0 ) { cdt->d = "first"; int r = cdt->x; list<string>::iterator b = d.end(); for(list<string>::const_iterator l = d.begin(); l != b; ++l) { cdt->next = new node; cdt = cdt->next; cdt->d = *l; cdt->x = ++r; } cdt->prev = cdt; cdt->next = 0; } cdt = root; cdt = cdt->next; cdt->prev = root; node last; if ( cdt != 0 ) { while ( cdt->next != 0 ) { cout << cdt->prev->d << " 2: " << cdt->prev->x << endl; cout << cdt->d << " 1: " << cdt->x << endl; last = *cdt; cdt = cdt->next; cdt->prev = &last; } cout << cdt->d << " 1: " << cdt->x << endl; cout << cdt->prev->d << " 2: " << cdt->prev->x << endl; cout << cdt->d << " 2: " << cdt->x << endl; } }

Share this post


Link to post
Share on other sites
"write a bidirectional iterator for my node class" != "write a function that takes an iterator"

its asking what it says, to write a bi-directional iterator type for your container.

I think you need to explain more, that is a bit strange that a book would make you write your own list type & use the standard library list type at the same time.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this