c – 如何实施尺寸有限的类似stl的容器?
发布时间:2020-12-16 10:28:02 所属栏目:百科 来源:网络整理
导读:在重构时,我想更改一个数组,其中条目被添加到std :: vector,但是为了兼容性(持久性,降级,……),它仍然需要有一个上限. 有一个类似stl的容器的最佳方式(优雅,类似stl,有限的额外代码)是多少,所以你知道插入一个条目失败了吗? 编辑: 为了澄清:我想要一个类
在重构时,我想更改一个数组,其中条目被添加到std :: vector,但是为了兼容性(持久性,降级,……),它仍然需要有一个上限.
有一个类似stl的容器的最佳方式(优雅,类似stl,有限的额外代码)是多少,所以你知道插入一个条目失败了吗? 编辑: 解决方法
一个简单的解决方案是将矢量封装在您自己的有限大小容器中.您可以使用私有组合或私有继承 – 注意私有继承模型的实现,并且没有公共继承的一些缺点.
编辑:具有私有继承的解决方案的草图 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需要更多可以添加到fa?ade的参数.如果您需要任何其他方法或typedef,您可以使用using声明将它们放入范围,重新定义typedef,或者使用您的特定测试实现适配器. 此外,在此实现中,size是编译时常量,但将其修改为构造函数参数非常简单. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |