distance
判斷加入數目兩個 Iterator 定址位置之間的。
template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance(
InputIterator _First,
InputIterator _Last
);
參數
_First
要判斷來自第二段距離第一個Iterator。_Last
要判斷距離(從開始的第二個Iterator。
傳回值
必須加入,直到等於 _Last_First 的次數。
備註
,當 InputIterator 滿足隨機存取Iterator時,需要的距離函式有常數複雜,否則,它會線性複雜,因此可能會耗用相當多的資源。
範例
// iterator_distance.cpp
// compile with: /EHsc
#include <iterator>
#include <list>
#include <iostream>
int main( )
{
using namespace std;
int i;
list<int> L;
for ( i = -1 ; i < 9 ; ++i )
{
L.push_back ( 2 * i );
}
list <int>::iterator L_Iter, LPOS = L.begin ( );
cout << "The list L is: ( ";
for ( L_Iter = L.begin( ) ; L_Iter != L.end( ); L_Iter++ )
cout << *L_Iter << " ";
cout << ")." << endl;
cout << "The iterator LPOS initially points to the first element: "
<< *LPOS << "." << endl;
advance ( LPOS , 7 );
cout << "LPOS is advanced 7 steps forward to point "
<< " to the eighth element: "
<< *LPOS << "." << endl;
list<int>::difference_type Ldiff ;
Ldiff = distance ( L.begin ( ) , LPOS );
cout << "The distance from L.begin( ) to LPOS is: "
<< Ldiff << "." << endl;
}
需求
標題: <iterator>
命名空間: std