如何使用C ++为我的容器Deque设置最大大小?

Thi*_*nha 1 c++ data-structures c++11

我需要帮助来定义Deque类型的STD容器的最大尺寸。

Deque文档C ++

在这种情况下,我将必须在数据结构中的给定子项中存储最大数量的客户端,如下例所示:

typedef struct Cart {
     int id;
     string clientName;
     int numberOfProducts;
     double purchaseValue;
} Cart;
Run Code Online (Sandbox Code Playgroud)

我定义了一个常量:

#define MAX_CLIENT 10
Run Code Online (Sandbox Code Playgroud)

我将定义队列,该队列最多必须有10个客户端:

deque<Cart> BOX_1(MAX_CLIENT);
deque<Cart> BOX_2(MAX_CLIENT);
deque<Cart> BOX_3(MAX_CLIENT);
Run Code Online (Sandbox Code Playgroud)

但似乎该结构仍然是动态的,甚至定义了最大数量。

感谢您的贡献。

eer*_*ika 5

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

deque<Cart> BOX_1(MAX_CLIENT);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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.