algorithm 中advance函数

来源:互联网 发布:网络大v 编辑:程序博客网 时间:2024/05/29 20:02

函数原型:

template <class InputIterator, class Distance>void advance (InputIterator& i, Distance n);
第一个参数为迭代器的引用,第二个参数是偏移位置,n = 0 不移动,n > 0 迭代器+n, n <0 迭代器-n。
作用:加减迭代器,即使是map这种非随机访问的容器也能使用。同样也适用于list/vector/deque/stack等容器中。使用起来比较方便
  1. #include <iostream>  
  2. #include <map>  
  3. #include <algorithm>  
  4. using namespace std;  
  5.   
  6. int _tmain(int argc, _TCHAR* argv[])  
  7. {  
  8.     map<intint> m;  
  9.     map<intint>::iterator it;   
  10.     int i = 0;  
  11.   
  12.     for (int i = 0; i != 50; ++i)  
  13.     {  
  14.         m.insert(make_pair(i, i));  
  15.     }  
  16.   
  17.     it = m.begin();  
  18.   
  19.     advance(it, 5);  
  20.   
  21.     cout << it->second;  
  22.   
  23.     return 0;  
  24. }  
原创粉丝点击