c++ distance 和advance函数

distance主要是用来求两个迭代器之间的元素个数

template<class InputIterator>
  typename iterator_traits<InputIterator>::difference_type
    distance (InputIterator first, InputIterator last);

Return distance between iterators
Calculates the number of elements betweenfirstandlast.



If i is a Random Access Iterator, the function usesoperator-to calculate this. Otherwise, the function uses the increase operator (operator++) repeatedly.

advance函数增加迭代器

template <class InputIterator, class Distance>
  void advance (InputIterator& i, Distance n);

Advance iterator
Advances the iteratoribynelements.

Distance:Distanceis any numerical type able to represent distances between iterators of this type.

#include <iostream>
#include <iterator>
#include <list>
using namespace std;

int main () {
  list<int> mylist;
  for (int i=0; i<10; i++) mylist.push_back (i*10);

  list<int>::iterator first = mylist.begin();
  list<int>::iterator last = mylist.end();

  cout << "The distance is: " << distance(first,last) << endl;//输出10

  list<int>::iterator it=mylist.begin();
  advance(it,5);
  cout<<*it; //输出50

  return 0;
}

深入:

http://www.cnblogs.com/woodfish1988/archive/2007/02/27/658498.html


原文链接: https://www.cnblogs.com/youxin/archive/2012/06/16/2552262.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/52831

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午4:14
下一篇 2023年2月9日 上午4:15

相关推荐