《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)
- 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; } |
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架