[英]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) 我想使用STL的列表,而不是创建自己的链接列表(我的代码如下所示)
struct myList
{
myList *next;
myList *previous;
};
myList->next = NULL;
Using STL list: 使用STL列表:
#include <list>
std::list<int> L;
L.push_back(1);
My question is, how to access the "next" element in STL's list? 我的问题是,如何访问STL列表中的“下一个”元素?
std::list
is a container. std::list
是一个容器。 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 :: 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.