STL迭代器辅助函数——advance

时间:2023-03-08 22:24:56
STL迭代器辅助函数——advance
Advance(i, n) increments the iterator i by the distance n. If n >  it is equivalent to executing ++i n times, and if n <  it is equivalent to executing --i n times. If n == , the call has no effect. 

advance(i, n)使得迭代器i增加一个长度n。如果n>,那么advance(i, n)等价于执行++i操作n次,如果n<,那么等价于执行- -i操作n次,如果n=,那么这个调用没有任何影响。 

Defined in the standard header iterator, and in the nonstandard backward-compatibility header iterator.h. 

定义在标准头文件<iterator>之中,也存在于向下兼容的(早期的STL)<iterator.h>头文件中。 

InputIterator is a model of Input Iterator.
Distance is an integral type that is convertible to InputIterator's distance type. 第一个参数i是 Input Iterator. n的类型应该可以转换成InputIterator's distance类型。 i is nonsingular.
Every iterator between i and i+n (inclusive) is nonsingular.
If InputIterator is a model of input iterator or forward iterator, then n must be nonnegative. If InputIterator is a model of bidirectional iterator or random access iterator, then this precondition does not apply.
对于随即存取迭代器,复杂度是O(),对于其他迭代器,复杂度是O(N)。 因为只有随机访问迭代器提供 + 和-运算符,该库提供两个模板函数、 advance() 和 distance()。
所需的页眉 <iterator> 原型 template<class InIt, class Dist> void advance(InIt& it, Dist n); 说明 高级函数接受两个参数:
初始化: 迭代器前进。
分发: 要通过将迭代器递增的元素数。
高级函数改进迭代器 n 次。该函数的随机访问迭代器类型迭代器时,计算表达式为
iterator += n. 否则,它通过评估执行的每一个增量:
++iterator. 如果迭代器输入或 n 的前向迭代器类型不能为负。 注意: 在原型的类/参数名称可能与中的头文件的版本不匹配。一些已被修改以提高可读性。
示例代码 //////////////////////////////////////////////////////////////////////
//
// Compile options needed: /GX
//
// <filename> : Advance.cpp
//
// Functions:
//
// advance()
//
// Written by Linda Koontz
// of Microsoft Product Support Services,
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////// /* Compile options needed: /GX
*/
#include <iostream>
#include <string>
#include <list> #if _MSC_VER > 1020 // if VC++ version is > 4.2
using namespace std; // std c++ libs implemented in std
#endif #pragma warning (disable:4786) typedef list<string, allocator<string> > STRLIST; void main() {
STRLIST List;
STRLIST::iterator iList;
STRLIST::difference_type dTheDiff; List.push_back("A1");
List.push_back("B2");
List.push_back("C3");
List.push_back("D4");
List.push_back("E5");
List.push_back("F6");
List.push_back("G7"); // Print out the list
iList=List.begin();
cout << "The list is: ";
for (int i = ; i < ; i++, iList++)
cout << *iList << " "; // Initialize to the first element"
iList=List.begin();
cout << "\n\nAdvance to the 3rd element." << endl;
advance(iList,);
cout << "The element is " << *iList << endl;
dTheDiff = distance( List.begin(), iList); } 程序的输出为:
The list is: A1 B2 C3 D4 E5 F6 G7 Advance to the 3rd element. The element is C3