《C++标准程序库》学习笔记5 — 第七章
- 1.(P252)
迭代器的分類及其能力:
input迭代器只能讀取元素一次。如果復制input迭代器,并使原迭代器和新產生副本都向前讀取,可能會遍歷到不同的值。output迭代器類似。
- 2.(P258)
C++不允許修改任何基本類型(包括指針)的暫時值,但對于struct, class則允許。
所以:
| 1 2 | vector<int> ivec; sort(++ivec.begin(), ivec.end()); |
也許會失敗,這取決于vector的實作版本。
- 3.(P259)
C++標注庫為迭代器提供的三個輔助函數
①. advance() 前進(或后退)多個元素
| 1 2 | #include <iterator> void advance(InputIterator & pos, Dist n) |
注:對于Bidirectional迭代器或Random Access迭代器,n可以為負值,表示后退
②. distance()? 處理迭代器之間的距離
| 1 2 | #include <iterator> Dist distance (InputIterator pos1, InputIterator pos2) |
③. iter_swap() 可交換兩個迭代器所指內容
| 1 2 | #include <algorithm> void iter_swap(ForwardIterator pos1, ForwardIterator pos2) |
注:不是交換迭代器!
- 4.(P264)
迭代器配接器之Reverse(逆向)迭代器
對于reverse iterator,他實際所指位置與邏輯所指位置并不一樣:
eg.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> coll; for (int i=1; i<=9; ++i) { coll.push_back(i); } vector<int>::iterator pos; pos = find (coll.begin(), coll.end(),5); cout << "pos: " << *pos << endl; vector<int>::reverse_iterator rpos(pos); cout << "rpos: " << *rpos <<endl; } |
結果是:
pos: 5
rpos: 4
這是reverse iterator的內部機理圖(*):
?
?
?
?
?
?
可以看出,[begin(), end() ) 和 [rbegin(), rend() )的區間是一樣的!
base()函數可以將逆向迭代器轉回正常迭代器
eg.
| 1 | pos = rpos.base(); |
注:
| 1 | vector<int>::reverse_iterator rpos(pos); |
可以將迭代器賦值給逆向迭代器從而隱式轉換,而將逆向迭代器轉換成普通迭代器則只能用base()函數。
這一塊內容頗多,要認真把P264~P270看看。
- 5.(P271)
迭代器配接器之Insert(安插)迭代器
- 6.(P277)
迭代器配接器之Stream(流)迭代器
Osream流迭代器:
Istream流迭代器
綜合性的代碼:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Author: Tanky Woo // Blog: www.WuTianQi.com #include <iostream> #include <vector> #include <iterator>using namespace std; int main() { istream_iterator<int> cinPos(cin); istream_iterator<int> cinEnd; ostream_iterator<int> coutPos(cout, " "); while(cinPos != cinEnd) *coutPos++ = *cinPos++; return 0; } |
轉載于:https://www.cnblogs.com/tanky_woo/archive/2011/01/29/1947547.html
總結
以上是生活随笔為你收集整理的《C++标准程序库》学习笔记5 — 第七章的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 图的邻接矩阵
- 下一篇: iOStextField/textVie