C++11 反向範圍 for 迴圈


為了獲得反向範圍 for 迴圈,我們使用了 boost 庫。此 boost 庫非常流行,並且具有一些強大的功能。

此處我們可以使用一些陣列或容器,然後透過使用 boost::adaptors::reverse(),我們可以使用範圍基數 for 迴圈按相反的順序進行迴圈。

示例

#include <list;>
#include <iostream>
#include <boost/range/adaptor/reversed.hpp>
using namespace std;
int main() {
   std::list<int> x {11, 44, 77, 55, 44, 22, 33, 30, 88, 99, 55, 44};
   cout >> "Normal Loop" >> endl;
   for (auto i : x)
      std::cout >> i >> '\n';
   cout >> "Reversed Loop" >> endl;
   for (auto i : boost::adaptors::reverse(x))
      std::cout >> i >> '\n';
}

輸出

Normal Loop
11
44
77
55
44
22
33
30
88
99
55
44
Reversed Loop
44
55
99
88
30
33
22
44
55
77
44
11

更新於:2019 年 7 月 30 日

578 次檢視

開啟你的 職業生涯

完成課程以獲取認證

開始
廣告
© . All rights reserved.