STL 中的 prev 函数可用来获取一个距离指定迭代器 n 个元素的迭代器,next 函数用来获取一个距离指定迭代器 n 个元素的迭代器。
template <class BidirectionalIterator> BidirectionalIterator prev (BidirectionalIterator it, typename iterator_traits<BidirectionalIterator>::difference_type n = 1);
参数
参数 描述 it 源迭代器,其类型只能为双向迭代器或者随机访问迭代器。 n 指定新迭代器距离 it 的距离,默认值为 1。 说明
该函数会返回一个距离 it 迭代器 n 个元素的新迭代器。
技术细节
当 n 为正数时,其返回的迭代器将位于 it 左侧;反之,当 n 为负数时,其返回的迭代器位于 it 右侧。
STL next函数详解
语法
template <class ForwardIterator> ForwardIterator next (ForwardIterator it, typename iterator_traits<ForwardIterator>::difference_type n = 1);
说明
其中 it 为源迭代器,其类似可以为前向迭代器、双向迭代器以及随机访问迭代器;n 为指定新迭代器距离 it 的距离,默认值为 1。该函数会返回一个距离 it 迭代器 n 个元素的新迭代器。
技术细节
当 it 为前向迭代器时,n 只能为正数,该函数最终得到的新迭代器位于 it 右侧;当 it 为双向迭代器或者随机访问迭代器时,若 n 为正数,则得到的新迭代器位于 it 右侧,反之位于 it 左侧。
案例
prev函数使用
prev函数使用
#include <iostream> #include <iterator> #include <list> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; std::list<int> mylist{10, 20, 30, 40, 50}; std::list<int>::iterator it = mylist.end(); auto newit = prev(it, 2); cout << "prev(it, 2) = " << *newit << endl; it = mylist.begin(); newit = prev(it, -2); cout << "prev(it, -2) = " << *newit; cout << endl; return 0; }
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ prev.cpp
编译后,我们直接运行生成的二进制文件
a.out
,如下图所示:我们通过 prev 函数,访问了 list 中的元素。可以看到,当 it 指向 mylist 容器最后一个元素之后的位置时,通过 prev(it, 2) 可以获得一个新迭代器 newit,其指向的是距离 it 左侧 2 个元素的位置(其存储的是元素 4)。
当 it 指向 mylist 容器中首个元素时,通过 prev(it, -2) 可以获得一个指向距离 it 右侧 2 个位置处的新迭代器。注意,prev() 函数自身不会检验新迭代器的指向是否合理,需要我们自己来保证其合理性。
next函数使用
next函数使用
#include <iostream> #include <iterator> #include <list> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; std::list<int> mylist{10, 20, 30, 40, 50}; std::list<int>::iterator it = mylist.end(); auto newit = next(it, 2); cout << "next(it, 2) = " << *newit << endl; it = mylist.end(); newit = next(it, -2); cout << "next(it, -2) = " << *newit; cout << endl; return 0; }
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ next.cpp
编译后,我们直接运行生成的二进制文件
a.out
,如下图所示:可以看到,和 prev() 函数恰好相反,当 n 值为 2 时,next(it, 2) 函数获得的新迭代器位于 it 迭代器的右侧,距离 2 个元素;反之,当 n 值为 -2 时,新迭代器位于 it 迭代器的左侧,距离 2 个元素。
注意,和 prev() 函数一样,next() 函数自身也不会检查新迭代器指向的有效性,需要我们自己来保证。
STL prev和next函数总结
STL 中的 prev 函数可用来获取一个距离指定迭代器 n 个元素的迭代器,next 函数用来获取一个距离指定迭代器 n 个元素的迭代器。