In standard c++ library, std::queue
has no function to check when it is full.
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.
std::queue
is full when its underlying container can't allocate memory to insert a new element.queue
.std::queue
and put the limit there. 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.