Home >Backend Development >C++ >How Can I Reverse Iterate Through a Container Using C 11's Range-Based for-Loops?
Reverse Iteration in Range-Based for-Loops with C 11
In C , the range-based for-loop provides a convenient way to iterate through the elements of a container. However, there is no built-in container adapter that can reverse the direction of iterators, making it challenging to iterate over a container in reverse order.
Concept: Container Adapters
Before exploring a solution, it's important to understand the concept of container adapters. These are objects that wrap a container and provide a modified view of its elements. Adapters can filter, transform, or otherwise manipulate the elements returned by the underlying container.
Solution: Boost's reverse Adapter
To reverse the direction of iterators and enable reverse iteration in range-based for-loops, we can leverage the boost::adaptors::reverse adapter from the Boost C Libraries. This adapter wraps a container and returns a reversed sequence of its elements.
Example
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 }; // Iterate in reverse order for (auto i : boost::adaptors::reverse(x)) std::cout << i << '\n'; // Iterate in forward order for (auto i : x) std::cout << i << '\n'; }
In this example, the reversed adapter is used to iterate over the list x in reverse order. The output will be:
19 17 13 11 7 5 3 2
Note: The boost::adaptors::reverse adapter is part of the Boost C Libraries, which is a collection of open-source libraries that can be downloaded and integrated into existing C projects.
The above is the detailed content of How Can I Reverse Iterate Through a Container Using C 11's Range-Based for-Loops?. For more information, please follow other related articles on the PHP Chinese website!