简体   繁体   中英

Is there a way to check when a queue from a standard library c++ is full?

In standard c++ library, std::queue has no function to check when it is full.

  1. Is there a way to know when it is full?
  2. If not, is there a way to limit its element (like queue limit n elements)?

The std::queue container adaptor doesn't have a member function that exports this. However, std::queue by default wraps a std::deque , which has a member function max_size() that returns the maximum supported size of the deque . If you need to use this functionality, you could switch and use deque rather than queue .

As a note, most implementations of deque::max_size will just return the maximum value of the integer type used to encode sizes, which likely is way larger than what you could actually fit into a deque . If you're using an embedded version of C++ the library implementers might have implemented max_size differently, but you shouldn't rely on this unless you have some implementation-specific documentation to that effect. Usually, std::deque just grows dynamically as elements are added and maxes out when no more memory is available as opposed to having a hard cap on the size.

  1. A std::queue is full when its underlying container can't allocate memory to insert a new element.
  2. You'll have to make that yourself, either by:
    • implementing a container capable of imposing a limit and use that in your queue .
    • inheriting std::queue and put the limit there.
    • wrapping the queue (composition) in a class that hides direct access to the queue and imposes the limit.

Here's a basic example of what implementing a container imposing the limit could look like. You'd need implement emplace_back etc. too for it to be really useful.

#include <iostream>
#include <new>
#include <queue>
#include <stdexcept>

// cheating by inheriting from std::deque
template<typename T, std::size_t max>
struct limited_deque : std::deque<T> {
    using std::deque<T>::deque;

    // the limit imposing push_back
    void push_back(const T& value) {
        if(this->size() == max) throw std::bad_alloc();
        // call the base class push_back
        std::deque<T>::push_back(value);
    }
};

// convenience alias
template<typename T, std::size_t max>
using limited_queue = std::queue<T, limited_deque<T, max>>;

int main() {
    limited_queue<int, 5> x;
    std::cout << "queue size : " << x.size() << "\n";

    try {
        for(int i = 0; i < 10; ++i) x.push(i);
    } catch(const std::exception& ex) {
        std::cout << ex.what() << "\n";
    }
    std::cout << "queue size : " << x.size() << "\n";
}

Very probable output:

queue size : 0
std::bad_alloc
queue size : 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM