เพื่อให้ได้ลูปตามช่วงที่ย้อนกลับ เราได้ใช้ไลบรารีบูสต์ ไลบรารีบูสต์นี้ได้รับความนิยมอย่างมากและมีฟังก์ชันการทำงานที่แข็งแกร่ง
ที่นี่เราสามารถใช้อาร์เรย์หรือคอนเทนเนอร์บางตัว จากนั้นโดยใช้ boost::adaptors::reverse() เราสามารถใช้ช่วงฐานสำหรับลูปในลำดับย้อนกลับได้
ตัวอย่าง
#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