具有常规STL接口的最大大小的数组,类似于boost :: array [英] Max-sized array with normal STL interface, similar to boost::array
问题描述
boost中是否有一个类似于array的类,它是一个类似于POD的类型,带有一个数组,但在容器中提供了可变数量的项目.也就是说,我想说的是数组最多包含10个项目,但在任何给定时刻可能包含0到10个项目.
Is there a class in boost similar to array which is a POD-like type with an array but provides for a variable number of items in the container. That is, I want to say the array has at most 10 items, but may contain from 0 to 10 items at any given moment.
boost::array
将size()
固定为常数N
,因此它不能作为向量替代品的替代品.特别是,我希望结构的读者不知道它是静态数组,他们可以像使用其他容器一样使用begin()
和end()
.
boost::array
unfortunately fixes size()
to the constant N
, so it can't work as a drop in replacement for a vector. In particular I'd like the readers of the structure not to know it is a static array, they can use begin()
and end()
like any other container.
很明显,如果push_back()
增长超出容量,则必须通过例外处理.
Obviously push_back()
would have to through an exception if it would grow beyond the capacity.
首选在boost
中已经存在的东西.
Something already in boost
would be preferred.
注意:必须是类似于 POD的数据类型.为了清楚起见,包括内容(它们本身将采用POD类类型)在内的整个数组类对象必须类似于POD.这是出于序列化/复制的原因(以及与该序列化/复制相关的性能).
NOTE: it must be a POD-like data type. For clarity, the entire array-like object, included the contents (which will themselves by POD-like types) must be POD-like. This is for serialization/copying reasons (and for performance related to that serialization/copying).
像POD一样,我的意思是:
By POD-like I mean:
- 具有编译时常量大小
- 可以放心地
对于那些说无效或不可能的人.对此没有什么独到之处. boost::array
是类似POD的类型.所要做的就是为当前大小添加一个额外的字段,以使其成为我想要的.我正在寻找已经存在的实现(因此已经过正确测试/维护).
For those who say it can't work or isn't possible. There is nothing ingenious about this. The boost::array
is a POD-like type. All it would take is adding one extra field, for the current size, to make that into what I want. I'm looking for an implementation that already exists (and is thus properly tested/maintained).
推荐答案
问题是(可能是)初始化.你如何初始化 大小(如果是POD)?您如何执行不变式 size()< = max_size?
The problem is (probably) initialization. How do you initialize the size, if it is a POD? How do you enforce the invariant size() <= max_size?
从技术上讲,定义一些东西很容易,但是是否 这是有用还是安全的是另一个问题.你为什么不 只需使用boost :: array,并保持当前大小为 一个单独的变量?
Technically, it would be easy to define something, but whether it would be useful or safe is another question. Why don't you just use boost::array, and maintain your current size as a separate variable?
- 詹姆斯·坎泽(James Kanze)
-- James Kanze
这篇关于具有常规STL接口的最大大小的数组,类似于boost :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!