Create Stack and Queue From Iterator Pair in C++23

Create Stack and Queue From Iterator Pair in C++23

Working with container adapters such as std::stack and std::queue often involves initializing them with elements stored in another container. A frequent scenario includes transferring values from a std::vector or another sequence container into these adapters. One common way to achieve this is by inserting elements individually, which introduces additional loops and makes the code more verbose than necessary.

For example, consider the following implementation:

#include <iostream>
#include <vector>
#include <stack>
#include <queue>

int main() {
    std::vector data = {1, 2, 3, 4};

    std::stack<int> s;
    for (int &it: data) {
        s.push(it);
    }

    std::queue<int> q;
    for (int &it: data) {
        q.push(it);
    }

    std::cout << s.top() << " " << q.front() << std::endl; // 4 1

    return 0;
}

In this example, both adapters are created empty and populated using loops. Each element from the source container is inserted separately. While this technique works correctly, it introduces repetitive code and slightly obscures the intent of initializing the adapters from an existing sequence.

Since C++23, this pattern is simplified by allowing std::stack and std::queue to be constructed directly from an iterator pair. This enables the adapters to be initialized from a range of elements in a single step. The result is less boilerplate and improved readability.

#include <iostream>
#include <vector>
#include <stack>
#include <queue>

int main() {
    std::vector data = {1, 2, 3, 4};

    std::stack s(data.begin(), data.end());
    std::queue q(data.begin(), data.end());

    std::cout << s.top() << " " << q.front() << std::endl; // 4 1

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.