Namespaces
Variants
Views
Actions

std::distance

From cppreference.com
< cpp‎ | iterator
Revision as of 15:17, 2 November 2012 by P12bot (Talk | contribs)

Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <iterator>
</td>

<td></td> <td></td> <tr class="t-dcl ">

<td class="t-dcl-nopad">
template< class InputIt >

typename std::iterator_traits<InputIt>::difference_type

    distance( InputIt first, InputIt last );
</td>

<td class="t-dcl-nopad"> </td> <td class="t-dcl-nopad"> </td> </tr> Template:ddcl list end

Returns the number of elements between first and last.

The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first.

Contents

Parameters

first - iterator pointing to the first element
last - iterator pointing to the last element
Type requirements
-
InputIt must meet the requirements of InputIterator. The operation is more efficient if InputIt additionally meets the requirements of RandomAccessIterator

Return value

The number of elements between first and last.

Complexity

Linear.

However, if InputIt additionally meets the requirements of RandomAccessIterator, complexity is constant.

Example

#include <iostream>
#include <iterator>
#include <vector>
 
int main() 
{
    std::vector<int> v{ 3, 1, 4 };
 
    auto distance = std::distance(v.begin(), v.end());
 
    std::cout << distance << '\n';
}

Output:

3

See also

Template:cpp/iterator/dcl list advance