Range Over Channels in C++

Our program demonstrates how to iterate over values received from a channel. In C++, we’ll use a queue from the standard library to simulate this behavior.

#include <iostream>
#include <queue>
#include <string>

int main() {
    // We'll iterate over 2 values in the queue.
    std::queue<std::string> queue;
    queue.push("one");
    queue.push("two");

    // This loop iterates over each element as it's
    // removed from the queue. The iteration terminates
    // after processing the 2 elements.
    while (!queue.empty()) {
        std::cout << queue.front() << std::endl;
        queue.pop();
    }

    return 0;
}

To run the program, compile it and then execute the resulting binary:

$ g++ range_over_queue.cpp -o range_over_queue
$ ./range_over_queue
one
two

This example demonstrates how to iterate over elements in a queue, which is similar to the channel iteration in the original example. However, C++ doesn’t have built-in channel support, so we use a queue as an analogous data structure.

In C++, we manually check if the queue is empty and remove elements, whereas in the original example, the range-based for loop automatically handled this for channel elements.

Note that in C++, unlike channels, queues don’t have a built-in closing mechanism. The loop continues until the queue is empty.