简体   繁体   中英

linked-list in C++ how to go to “next element” using STL list

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?

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;

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;

use an iterator :

std::list<int>::iterator i = L.begin();
std::list<int>::iterator i_end = L.end();
while(i!=i_end)
   {
   ++i;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM