Home >Backend Development >C++ >Can C 11 Range-Based For Loops Iterate in Reverse?
Reverse Range-Based Iteration with C 11
Question:
Is there a way to reverse the direction of iterators for a range-based for-loop? Currently, transforming a standard for-loop with explicit iterators using rbegin() and rend() is possible, but it would be advantageous to have an analogous syntax for the range-based version.
Answer:
Rather than creating a custom adapter, Boost offers a convenient solution with boost::adaptors::reverse. This adapter reverses the order of elements while iterating.
Usage Example:
#include <list> #include <iostream> #include <boost/range/adaptor/reversed.hpp> int main() { std::list<int> x { 2, 3, 5, 7, 11, 13, 17, 19 }; for (auto i : boost::adaptors::reverse(x)) std::cout << i << '\n'; for (auto i : x) std::cout << i << '\n'; }
The above is the detailed content of Can C 11 Range-Based For Loops Iterate in Reverse?. For more information, please follow other related articles on the PHP Chinese website!