【问题标题】:How do I get the second element in a standard list如何获取标准列表中的第二个元素
【发布时间】:2015-10-26 20:50:16
【问题描述】:

我正在使用 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
}

【问题讨论】:

标签: c++ c++11


【解决方案1】:

如果您确实在使用 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 个位置,它将指向的元素。

【讨论】:

  • 谢谢,虽然那没有做我想要的工作,但还是谢谢你
  • 这很好,但如果答案有误,我可以删除或修复它:-) 你的意思是它正确回答了问题,但你的问题不是解决实际问题的方法吗?
  • 不,我试过了,但是对于我尝试使用列表的问题,结果不起作用,所以我需要使用不同的数据结构。
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 2017-10-27
  • 2019-10-23
  • 2015-07-15
  • 2017-02-11
  • 2019-08-07
  • 1970-01-01
相关资源
最近更新 更多