| 迭代器辅助函数 | 功能 |
|---|---|
| advance(it, n) | it 表示某个迭代器,n 为整数。该函数的功能是将 it 迭代器前进或后退 n 个位置。 |
| distance(first, last) | first 和 last 都是迭代器,该函数的功能是计算 first 和 last 之间的距离。 |
| begin(cont) | cont 表示某个容器,该函数可以返回一个指向 cont 容器中第一个元素的迭代器。 |
| end(cont) | cont 表示某个容器,该函数可以返回一个指向 cont 容器中最后一个元素之后位置的迭代器。 |
| prev(it) | it 为指定的迭代器,该函数默认可以返回一个指向上一个位置处的迭代器。注意,it 至少为双向迭代器。 |
| next(it) | it 为指定的迭代器,该函数默认可以返回一个指向下一个位置处的迭代器。注意,it 最少为前向迭代器。 |
template <class InputIterator, class Distance>
void advance (InputIterator& it, Distance n);
<iterator>头文件,并位于 std 命名空间中。因此,程序在使用该函数之前,应包含如下 2 行代码:
#include <iterator> using namespace std;
第二行代码不是必须的,但如果不引用,则后续在使用 advance() 函数时,需要额外标注 std 命名空间(强烈建议初学者使用)。
#include <iostream> // std::cout
#include <iterator> // std::advance
#include <forward_list>
using namespace std;
int main() {
//创建一个 forward_list 容器
forward_list<int> mylist{1,2,3,4};
//it为前向迭代器,其指向 mylist 容器中第一个元素
forward_list<int>::iterator it = mylist.begin();
//借助 advance() 函数将 it 迭代器前进 2 个位置
advance(it, 2);
cout << "*it = " << *it;
return 0;
}
程序执行结果为:
*it = 3
此程序中,由于 it 为前向迭代器,其只能进行 ++ 操作,即只能前进(右移),所以 advance() 函数的第 2 个参数只能为正数。
#include <iostream> // std::cout
#include <iterator> // std::advance
#include <vector>
using namespace std;
int main() {
//创建一个 vector 容器
vector<int> myvector{1,2,3,4};
//it为随机访问迭代器,其指向 myvector 容器中第一个元素
vector<int>::iterator it = myvector.begin();
//借助 advance() 函数将 it 迭代器前进 2 个位置
advance(it, 2);
cout << "1、*it = " << *it << endl;
//继续使用it,其指向 myvector 容器中最后一个元素之后的位置
it = myvector.end();
//借助 advance() 函数将 it 迭代器后退 3 个位置
advance(it, -3);
cout << "2、*it = " << *it;
return 0;
}
程序执行结果为:
1、*it = 3
2、*it = 2
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有