Home >Backend Development >C++ >How Can Boost::adaptors::reverse Enable Reverse Range-Based For-Loops in C 11?
C 11 Reverse Range-Based For-Loop Using Boost
Iterating through containers in reverse order can be achieved using a dedicated container adapter that reverses the direction of iterators. This allows us to implement reverse iteration with the convenience of range-based for-loops.
Fortunately, Boost provides such an adapter: boost::adaptors::reverse. This adapter takes a container as input and returns a new container adapter with reversed iterators.
To demonstrate its usage, consider the following 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'; }
This code first creates a list x of integers. Then it iterates over the list in reverse order using the boost::adaptors::reverse(x) adapter. It prints the elements in reverse order, followed by the original order for comparison.
The output of the program is:
19 17 13 11 7 5 3 2 2 3 5 7 11 13 17 19
This demonstrates the ability of the Boost boost::adaptors::reverse adapter to reverse the direction of iterators and allow for convenient reverse iteration with range-based for-loops in C .
The above is the detailed content of How Can Boost::adaptors::reverse Enable Reverse Range-Based For-Loops in C 11?. For more information, please follow other related articles on the PHP Chinese website!