c++ - 如何获取标准列表中的第二个元素

标签 c++ c++11

我正在使用 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++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);

Get iterator to next element. Returns an iterator pointing to the element that it would be pointing to if advanced n positions.

关于c++ - 如何获取标准列表中的第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33355356/

相关文章:

c++ - 唯一键和散列的无序映射

c++ - 无法使用 cuda 进入 __global__ 函数

c++ - 无法理解 std::thread 用法

c++ - 如何在大型项目中使用 -fsplit-stack

php - Swig 将 vector<std::string> 转换为原生 PHP 数组

c++ - 了解工厂方法和静态变量分配的返回值优化 (Visual Studio)

c# - 从 C# 访问 C++ DLL 库

c++ - 将 lexical_cast double boost 为字符串,给出无效结果

c++ - 是否可以使shared_ptr协变?

c++ - 无法使用 C++ 在 Matlab 上打开重新采样的图像