Home >Backend Development >C++ >How Can I Reverse a Range-Based For-Loop in C Using Boost.Range?

How Can I Reverse a Range-Based For-Loop in C Using Boost.Range?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 18:11:15713browse

How Can I Reverse a Range-Based For-Loop in C   Using Boost.Range?

Reverse Range-Based For-Loops in C 11 with Boost.Range

In C , the range-based for-loop is a powerful tool for iterating over containers. However, by default, it iterates from the beginning of the container to the end. Is there a way to reverse this direction?

Reverse Iterators with the Range-Based For-Loop

One way to iterate over a container in reverse is to use the rbegin() and rend() member functions. However, this requires the use of explicit iterators and can become unwieldy for complex scenarios:

for (auto i = c.rbegin(); i != c.rend(); ++i) { ... }

Boost.Range's Reverse Adapter

Fortunately, Boost.Range provides an elegant solution with the boost::adaptors::reverse adapter. This adapter wraps a container and reverses the direction of its iterators. This allows for seamless integration with range-based for-loops:

for (auto& i : boost::adaptors::reverse(c)) { ... }

Usage Example

Here's an example of using boost::adaptors::reverse to iterate over a list in reverse order:

#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';
    }
    return 0;
}

Output:

19
17
13
11
7
5
3
2
2
3
5
7
11
13
17
19

The above is the detailed content of How Can I Reverse a Range-Based For-Loop in C Using Boost.Range?. 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