首页 > 编程 > C++ > 正文

C++:distance()

2019-11-06 09:27:43
字体:
来源:转载
供稿:网友

function template std::distance template typename iterator_traits::difference_type distance (InputIterator first, InputIterator last); Return distance between iterators Calculates the number of elements between first and last.

If it is a random-access iterator, the function uses Operator- to calculate this. Otherwise, the function uses the increase operator (operator++) repeatedly.

Parameters first: Iterator pointing to the initial element. last: Iterator pointing to the final element. This must be reachable from first. InputIterator shall be at least an input iterator.

Return value The number of elements between first and last.

Example // advance example

#include <iostream> // std::cout#include <iterator> // std::distance#include <list> // std::listint main () { std::list<int> mylist; for (int i=0; i<10; i++) mylist.push_back (i*10); std::list<int>::iterator first = mylist.begin(); std::list<int>::iterator last = mylist.end(); std::cout << "The distance is: " << std::distance(first,last) << '/n'; return 0;}

Output:

The distance is: 10


上一篇:c++

下一篇:C++ 注意点

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选