迭代器的輔助函式
stl 中有用於操作迭代器的三個函式模板,它們是:
advance(p, n):使迭代器 p 向前或向後移動 n 個元素。
distance(p, q):計算兩個迭代器之間的距離,即迭代器 p 經過多少次 + + 操作後和迭代器 q 相等。如果呼叫時 p 已經指向 q 的後面,則這個函式會陷入死迴圈。
iter_swap(p, q):用於交換兩個迭代器 p、q 指向的值。
要使用上述模板,需要包含標頭檔案 algorithm。下面的程式演示了這三個函式模板的 用法。
#include
#include
#include
//要使用操作迭代器的函式模板,需要包含此檔案
using
namespace std;
intmain()
; list <
int>
lst(a, a+5)
; list <
int>
::iterator p = lst.
begin()
;advance
(p,2);
//p向後移動兩個元素,指向3
cout <<
"1)"
<<
*p << endl;
//輸出 1)3
advance
(p,-1)
;//p向前移動乙個元素,指向2
cout <<
"2)"
<<
*p << endl;
//輸出 2)2
list<
int>
::iterator q = lst.
end();
q--;//q 指向 5
cout <<
"3)"
<<
distance
(p, q)
<< endl;
//輸出 3)3
iter_swap
(p, q)
;//交換 2 和 5
cout <<
"4)"
;for
(p = lst.
begin()
; p != lst.
end();
++p)
cout <<
*p <<
" ";
return0;
}
迭代器和輔助函式
迭代器 iterator 是連線容器和演算法的紐帶,為資料提供了抽象,使寫演算法的人不必關心各種資料結構的細節。迭代器提供了資料訪問的標準模型 物件序列,使對容器更廣泛的訪問操作成為可能。根據迭代器所支援的操作不同,在 stl中定義了如下 5種迭代器 迭代器類別 說明輸入 從容器中讀取元素。輸入迭代...
C STL迭代器輔助函式
平時零零碎碎用過,今天總結一下?該函式有多個過載,可以用於各類容器迭代器,可以讓乙個迭代器一次前進若干個元素,很好懂,舉個栗子 include include using namespace std intmain 輸出結果 1 32 include include using namespace ...
迭代器的輔助函式例項
問題及 檔名稱 main.cpp 作 者 崔青青 完成日期 2016年6月3日 版 本 號 v1.0 問題描述 輸入描述 無 輸出描述 無 include include include includeusing namespace std int main list iterator pos co...