views:

384

answers:

3

I have a very basic question. I want to use STL's list instead of creating my own linked-list ( my code is shown below)

struct myList
{

    myList *next;
    myList *previous;
};

myList->next = NULL;

Using STL list:

#include <list>

std::list<int> L;
L.push_back(1);

My question is, how to access the "next" element in STL's list?

+1  A: 

use an iterator:

std::list<int>::iterator i = L.begin();
std::list<int>::iterator i_end = L.end();
while(i!=i_end)
   {
   ++i;
   }
Pierre
Woah, now that's a piece of incorrect code...
Kornel Kisielewicz
Yeap, ++ i was the key.. Thanks!
cppb
what exactly is this piece of code meant to illustrate?
Idan K
+5  A: 

std::list is a container. To access individual nodes, you need to use an iterator.

For example, to get the head node, you use

std::list<int>::const_iterator cit = L.begin();

To move to the next node, you use

++ cit;
KennyTM
Thank you very much!
cppb
+3  A: 

Use std::advance:

std::list<int> mylist;
...
int index = 5;
std::list<int>::iterator ith_iterator = mylist.begin();
std::advance(ith_iterator, index);
int& ith_element = *ith_iterator;
Idan K