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
Release: 2024-12-02 15:58:10
Original
985 people have browsed it

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 };
Copy after login

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';
Copy after login

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';
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template