Home >Backend Development >C++ >How Can I Easily Reverse Iterate Through a Container Using C 11 Range-Based For-Loops?

How Can I Easily Reverse Iterate Through a Container Using C 11 Range-Based For-Loops?

DDD
DDDOriginal
2024-12-02 15:58:10924browse

How Can I Easily Reverse Iterate Through a Container Using C  11 Range-Based For-Loops?

C 11 Reverse Range-Based For-Loops

Iterating over a container in reverse order with range-based for-loop requires reversing the direction of iterators. While explicit iterators provide a straightforward solution, is there a convenient container adapter that offers this functionality?

Reverse Iterator Adapter

Fortunately, the Boost library includes a solution: boost::adaptors::reverse. This adaptor reverses the iteration order of a container, enabling range-based for-loops to iterate in reverse.

Example Usage

Consider a container of integers:

std::list<int> x { 2, 3, 5, 7, 11, 13, 17, 19 };

To iterate over this container in reverse using a range-based for-loop, use the reverse adaptor:

for (auto i : boost::adaptors::reverse(x))
    std::cout << i << '\n';

This will print the elements of the list in reverse order.

Comparison to Original Iteration

For comparison, here is the original iteration order without the reverse adaptor:

for (auto i : x)
    std::cout << i << '\n';

This will print the elements of the list in their original order.

Conclusion

Boost's reverse adaptor provides a convenient way to iterate over a container in reverse order using range-based for-loops. This simplifies code and allows for more concise and efficient reverse iteration.

The above is the detailed content of How Can I Easily Reverse Iterate Through a Container Using C 11 Range-Based For-Loops?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn