如何使用reverse_iterator? (C/C++) (STL)

來源:互聯網
上載者:User

若要將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
13using namespace std;
14int 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
請按任意鍵繼續 . . .

19行的for loop,使用了reverse_iterator,讓我們很簡單的如操作一般的iterator般去處理reverse_iterator。

25行到29行,使用了一般的iterator去處理,程式有點詭異,主要是讓我們看出,若沒有reverse_iterator,程式有多難寫。

copy() algorithm也可搭配reverse_iterator,只需一行就可以了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.