std::distance
STD::距离
Defined in header | | |
---|---|---|
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) |
返回跳数。first
到last
...
参数
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的要求,则操作效率更高。
返回值
需要增加的数目first
到last
如果使用随机访问迭代器,则值可能为负值first
可从last
%28自C++11%29。
复杂性
线性的。
但是,如果InputIt
额外满足RandomAccessIterator
,复杂性是不变的。
例
二次
#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';
}
二次
产出:
二次
distance(first, last) = 3
distance(last, first) = -3
二次
另见
advance | advances an iterator by given distance (function) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。