There is no such container in the C++ standard library, but you can easily create your own by wrapping an existing container. std::deque
may be appropriate, because it's designed to allow fast insertion and deletion at both ends.
template <class T, int MaxSize>
class CircularContainer
{
static_assert(MaxSize >= 0);
public:
void Add(T const& t)
{
if (MaxSize > 0)
{
if (size(data) == MaxSize)
{
data.pop_front();
}
data.push_back(t);
}
}
// ...
private:
std::deque<T> data;
};
There are a lot of design decisions to make here, for example:
- Should be the maximum size be completely static, set in the constructor or possibly be modifiable even after a container object has been created?
- Which iterators and references to elements are allowed to become invalid by operations like
Add
?
- Which parts of the wrapped container's interface does your container need to expose? Does it need its own iterator classes, does it have to work with range-based
for
loops, and so on.
- Do you wish to allow a maximum size of zero, and do you need to optimise the corresponding checks with template specialisation or
constexpr if
?
- Should the wrapped container class itself be a template parameter, just like
std::stack
does it?
Most of those design decisions will depend on whether the container will be used in library code or in application code.