如何获得标准列表中的第二个元素

问题描述:

我在C++标准库中使用了一个列表,我想知道如何使用迭代器获得第二个元素。我有两个迭代器,我希望迭代器2前进1个节点。如何获得标准列表中的第二个元素

intPaint(string input){ 
list<char>sequence (input.begin,input.end); 
int count; 
list<char>::iterator ptr1= sequence.begin(); 
list<char>::iterator ptr2= ?// I want to get the second node 
...//rest of the code isn't important it just checks the characters and moves 
//the iterator 
} 
+0

[皮克在STL容器的下一个元素]的可能的复制(http://stackoverflow.com/questions/3673684/peek-the-next-element-in-stl-container) –

如果你确实使用C++ 11,然后std::next()应该做的伎俩:

list<char>::iterator ptr1 = sequence.begin(); 
list<char>::iterator ptr2 = std::next(sequence.begin()) 

documentation

template <class ForwardIterator> 
ForwardIterator next(ForwardIterator it, 
        typename iterator_traits<ForwardIterator>::difference_type n = 1); 

获取迭代器下一个元素。返回一个指向 元素的迭代器,它将指向高级n位置的元素。

+0

感谢尽管这没” t做我想要的工作,但无论如何感谢你 – btm

+0

这很好,但如果答案错了,我可以删除或修复它:-)你的意思是它正确回答了这个问题,但你的问题不是你的方式实际问题? – WhiteViking

+0

不,我试过,但对于我试图使用列表的结果是不起作用的问题,所以我需要使用不同的数据结构。 – btm