如何实现一个大小有限的类似stl的容器?

ste*_*anv 3 c++ refactoring stl

在重构时,我想更改一个数组,其中条目被添加到std :: vector,但是为了兼容性(持久性,降级,......),它仍然需要有一个上限.
有一个类似stl的容器的最佳方式(优雅,类似stl,有限的额外代码)是多少,所以你知道插入一个条目失败了吗?

编辑:
澄清:我想要一个类似stl的容器,它开始为空,你可以填充条目并可能删除条目并迭代填充的条目,但这不允许输入超过例如50个条目,所以几乎像一个顺序的对手,但有一个上限.

Dav*_*eas 5

一个简单的解决方案是将矢量封装在您自己的有限大小容器中.您可以使用私有组合或私有继承 - 注意私有继承模型的实现,并且没有公共继承的一些缺点.

编辑:具有私有继承的解决方案的草图

template <typename T, unsigned int N>
class fixed_vector : std::vector<T>
{
    typedef std::vector<T> vector_type;
public:
    typedef typename vector_type::reference reference;
    typedef typename vector_type::const_reference const_reference;
    typedef typename vector_type::iterator iterator;
    typedef typename vector_type::const_iterator const_iterator;
    typedef typename vector_type::value_type value_type;
    typedef typename vector_type::size_type size_type;

    fixed_vector() : vector_type() {}
    fixed_vector( size_type size, value_type const & value = value_type() )
       : vector_type(size,value)
    {}      

    void push_back( value_type v ) {
        ensure_can_grow();
        vector_type::push_back( v );
    }
    iterator insert( iterator position, value_type const & v ) {
        ensure_can_grow();
        vector_type::insert( position, v );
    }
    void reserve( size_type size ) {
        if ( size > N ) throw std::invalid_argument();
        vector_type::reserve( size );
    }
    size_type capacity() const {
        // In case the default implementation acquires by default 
        // more than N elements, or the vector grows to a higher capacity
        return std::min( vector_type::capacity(), N );
    }
    // provide other insert methods if required, with the same pattern
    using vector_type::begin;
    using vector_type::end;
    using vector_type::operator[];
    using vector_type::erase;
    using vector_type::size;
    using vector_type::empty;
private:
    void ensure_can_grow() const {
        // probably a different exception would make sense here: 
        if ( this->size() == N ) throw std::bad_alloc();
    }
};
Run Code Online (Sandbox Code Playgroud)

那里有相当多的挥手...... std::vector采取更多可以添加到外墙的论据.如果您需要任何其他方法或typedef,您可以使用using声明将它们带入范围,重新定义typedef,或者使用您的特定测试实现适配器.

此外,在此实现中,size是编译时常量,但将其修改为构造函数参数非常简单.