'How to set a maximum size for my container Deque with C ++?

I need help defining a maximum size of my STD container of type Deque.

Deque Documentation C++

In this case, I would have to store a maximum number of clients in a given child in a data structure as in the example below:

typedef struct Cart {
     int id;
     string clientName;
     int numberOfProducts;
     double purchaseValue;
} Cart;

I defined a constant:

#define MAX_CLIENT 10

And I'm about to define the queues, which must have a maximum of 10 clients:

deque<Cart> BOX_1(MAX_CLIENT);
deque<Cart> BOX_2(MAX_CLIENT);
deque<Cart> BOX_3(MAX_CLIENT);

But it seems that the structure is still dynamic, even defining the maximum number.

Thanks for the contribution.



Solution 1:[1]

I'm about to define the queues, which must have a maximum of 10 clients:

deque<Cart> BOX_1(MAX_CLIENT);

To clarify, that creates a deque that contains 10 carts initially.

How to set a maximum size for my container Deque with C ++?

std::deque does not support such feature. It is not possible to set a maximum size for it. There isn't any standard container that supports such feature (except technically std::array which has a fixed size).

You can yourself write a custom container that does support such feature. You can use a standard container within the implementation of your custom container if you so prefer. A minimal example, which is by no means complete, nor polished:

struct MaxContainer {
    void push_front(Cart c) {
        if (internal_container.size() < max_size)
            internal_container.push_front(std::move(c));
        else
            ; // do something else
    }
private:
    int max_size;
    std::deque<Cart> internal_container;
}

You could even create a container adaptor, which can adapt any container (with restrictions) and add a max size to it simply by templetizing the internal container type.


That said, you don't necessarily need to have a container which enforces the size limit. Instead, you could simply refrain from adding more elements into the container in the code that uses it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community