若要將vector中反過來列印,該怎麼做呢?STL提供了reverse_iterator。
1
/**/
/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : ReverseIterator.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use reverse_iterator
7Release : 12/17/2006 1.0
8*/
9 #include < iostream >
10 #include < vector >
11 #include < algorithm >
12
13 using namespace std;
14 int main() {
15 int ia[] = {1, 2, 3};
16 vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
17
18 // use reverse_iterator by for loop
19 for(vector<int>::reverse_iterator r_iter = ivec.rbegin(); r_iter != ivec.rend(); ++r_iter)
20 cout << *r_iter << " ";
21
22 cout << endl;
23
24 // use ordinary iterator to print reversely
25 for(vector<int>::const_iterator iter = (--ivec.end()); iter >= ivec.begin();iter--) {
26 cout << *iter << " ";
27 if (iter == ivec.begin())
28 break;
29 }
30
31 cout << endl;
32
33 // use reverse_iterator with copy() algorithm
34 copy(ivec.rbegin(), ivec.rend(), ostream_iterator<int>(cout, " "));
35 cout << endl;
36}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : ReverseIterator.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use reverse_iterator
7Release : 12/17/2006 1.0
8*/
9 #include < iostream >
10 #include < vector >
11 #include < algorithm >
12
13 using namespace std;
14 int main() {
15 int ia[] = {1, 2, 3};
16 vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
17
18 // use reverse_iterator by for loop
19 for(vector<int>::reverse_iterator r_iter = ivec.rbegin(); r_iter != ivec.rend(); ++r_iter)
20 cout << *r_iter << " ";
21
22 cout << endl;
23
24 // use ordinary iterator to print reversely
25 for(vector<int>::const_iterator iter = (--ivec.end()); iter >= ivec.begin();iter--) {
26 cout << *iter << " ";
27 if (iter == ivec.begin())
28 break;
29 }
30
31 cout << endl;
32
33 // use reverse_iterator with copy() algorithm
34 copy(ivec.rbegin(), ivec.rend(), ostream_iterator<int>(cout, " "));
35 cout << endl;
36}
執行結果
3
2
1
3 2 1
3 2 1
請按任意鍵繼續 . . .
3 2 1
3 2 1
請按任意鍵繼續 . . .
19行的for loop,使用了reverse_iterator,讓我們很簡單的如操作一般的iterator般去處理reverse_iterator。
25行到29行,使用了一般的iterator去處理,程式有點詭異,主要是讓我們看出,若沒有reverse_iterator,程式有多難寫。
copy() algorithm也可搭配reverse_iterator,只需一行就可以了。