c++ - 一个有大小限制的类STL容器应该如何实现?

标签 c++ stl refactoring

在重构时,我想更改一个数组,其中将条目添加到 std::vector,但为了兼容性(持久性、降级...),它仍然需要有一个上限。
拥有大小有限的类似 STL 的容器的最佳方式是什么(优雅的、类似 STL 的、有限的额外代码),因此您知道插入条目失败?

编辑:
澄清一下:我想要一个类似 STL 的容器,它开始是空的,您可以填充条目并可能删除条目并迭代填充的条目,但不允许放入超过例如50 个条目,几乎就像一个顺序容器,但有一个上限。

最佳答案

一个简单的解决方案是将 vector 封装在您自己的有限大小容器中。您可以使用私有(private)组合或私有(private)继承——请注意,私有(private)继承模型根据实现,并且没有公共(public)继承的一些缺点。

编辑:私有(private)继承解决方案草图

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();
    }
};

那里有相当多的挥手...... std::vector 接受更多可以添加到外观的参数。如果您需要任何其他方法或 typedef,您只需使用 using 声明将它们引入范围,重新定义 typedef,或使用您的特定测试实现适配器。

此外,在这个实现中,大小是一个编译时常量,但将它修改为构造函数参数会非常简单。

关于c++ - 一个有大小限制的类STL容器应该如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3563591/

相关文章:

c++ - 在 C++ 中实现公钥加密的简单方法?

c++ - 此函数使 .exe 崩溃,我做错了什么?

c++ - 无法对存储在容器中的指针调用公共(public)方法

c++ - 最佳实践 : How to improve this code that sums container values?

python - 重构重复的 if 语句

c# - 在 C#(或任何语言)中,你最喜欢的删除重复的方法是什么?

c# - 应该如何从两个几乎相同的 Controller Action 转移到一个处理两个必要任务的 Action ?

c++ - 使用bazel从源代码构建 tensorflow 服务遇到错误: C++ compilation of rule '@org_tensorflow//…' failed (Exit 4)

c++ - 想在同一背景上放置多个透明颜色的图像

c++ - 使用 "approximate"STL 贴图