开发者

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

开发者 https://www.devze.com 2022-12-15 18:54 出处:网络
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)

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;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消