首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::distance

Defined in header <iterator>

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

(until C++17)

template< class InputIt > constexpr typename std::iterator_traits<InputIt>::difference_type distance( InputIt first, InputIt last );

(since C++17)

返回跳数。firstlast...

参数

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

(until C++11)

If InputIt is not RandomAccessIterator, the behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first. If InputIt is RandomAccessIterator, the behavior is undefined if last is not reachable from first and first is not reachable from last.

(since C++11)

first

-

iterator pointing to the first element

last

-

iterator pointing to the end of the range

类型要求

-输入必须符合输入器的要求。如果InputIt能满足RandomAccessIterator的要求,则操作效率更高。

返回值

需要增加的数目firstlast如果使用随机访问迭代器,则值可能为负值first可从last%28自C++11%29。

复杂性

线性的。

但是,如果InputIt额外满足RandomAccessIterator,复杂性是不变的。

二次

代码语言:javascript
复制
#include <iostream>
#include <iterator>
#include <vector>
 
int main() 
{
    std::vector<int> v{ 3, 1, 4 };
    std::cout << "distance(first, last) = "
              << std::distance(v.begin(), v.end()) << '\n'
              << "distance(last, first) = "
              << std::distance(v.end(), v.begin()) << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
distance(first, last) = 3
distance(last, first) = -3

二次

另见

advance

advances an iterator by given distance (function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券