STL 中的 advance() 函数用于将迭代器前进(或者后退)指定长度的距离。
#include <iterator> using namespace std;
说明
值得一提的是,advance() 函数定义在
<iterator>
头文件,并位于 std 命名空间中。STL advance函数详解
语法
template <class InputIterator, class Distance> void advance (InputIterator& it, Distance n);
参数
参数 描述 it 目标迭代器。 n 通常为一个整数。 说明
如果 it 为输入迭代器或者前向迭代器,则 n 必须为一个正数,即表示将 it 右移(前进) n 个位置;反之,如果 it 为双向迭代器或者随机访问迭代器,则 n 为正数时表示将 it 右移(前进) n 个位置,n 为负数时表示将 it 左移(后退) n 个位置。
技术细节
根据 it 类型是否为随机访问迭代器,advance() 函数底层采用了不同的实现机制:
- 当 it 为随机访问迭代器时,由于该类型迭代器支持 p+n 或者 p-n(其中 p 就是一个随机访问迭代器)运算,advance() 函数底层采用的就是 it+n 操作实现的;
- 当 it 为其他类型迭代器时,它们仅支持进行 ++ 或者 – 运算,这种情况下,advance() 函数底层是通过重复执行 n 个 ++ 或者 – 操作实现的。
案例
advance操作list
使用 advance 操作 forward_list
#include <iostream> #include <iterator> #include <forward_list> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; forward_list<int> mylist{1024, 110, 99, 200}; forward_list<int>::iterator it = mylist.begin(); advance(it, 2); cout << "*it = " << *it; cout << endl; return 0; }
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ reverse_iterator.cpp -std=c++11
编译后,我们直接运行生成的二进制文件
a.out
,如下图所示:此程序中,由于 it 为前向迭代器,其只能进行 ++ 操作,即只能前进(右移),所以 advance() 函数的第 2 个参数只能为正数。
advance操作vector
使用 advance 操作 vector
#include <iostream> #include <iterator> #include <vector> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; vector<int> myvector{1,2,3,4}; vector<int>::iterator it = myvector.begin(); advance(it, 2); cout << "*it = " << *it << endl; it = myvector.end(); advance(it, -3); cout << "*it = " << *it; cout << endl; return 0; }
我们在 Linux 下使用 g++ 进行编译,具体命令如下: