开发者

C++ Fixed size container with swappable elements

开发者 https://www.devze.com 2023-03-17 20:59 出处:网络
I\'m se开发者_运维知识库arching for a container with the following functionality: Fixed size at runtime. Thus, memory shouldn\'t be allocated in little chunks (like std::list does).

I'm se开发者_运维知识库arching for a container with the following functionality:

  • Fixed size at runtime. Thus, memory shouldn't be allocated in little chunks (like std::list does).
  • Elements should be swappable (Something like std::list::splice offers).

EDIT: Thinking of a list: I just need to move elements from an arbitrary position to the front. EDIT2: I would like to use something like a std::list, but takes advantage of a runtime fixed size.


I'd think of TR1 array:

std::array<T, int>

Or, if you haven't got that yet,

boost::array<T, int>

Which is identical for all intents and purposes. Of course the validity of std::swap on elements depends on availability of proper copy constructor/assignment operator.


It's not too clear to me what you are looking for. Two solutions come to mind: std::vector (created with the maximum size), coupled with a good implementation of swap for your objects, or a custom allocator for std::list, which pre-allocates the number of nodes you'll need in a single block.


You can specify the (initial) size of an std::list at construction time :

std::list<Type> myList = std::list<Type>(10);

You can still grow/shrink it afterwards, but the list will contain 10 default constructed Type objects from the start.

Does that suit your needs ?


std::vector ?

Array based. Can specify the size and has a swap function.

You haven't said what you'll be using it for so I don't really know if you're going to have any speed issues with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消