0xbadf00d
0xbadf00d

Reputation: 18216

C++ Fixed size container with swappable elements

I'm searching for a container with the following functionality:

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.

Upvotes: 1

Views: 352

Answers (4)

hookenz
hookenz

Reputation: 38997

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.

Upvotes: 0

Sander De Dycker
Sander De Dycker

Reputation: 16243

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 ?

Upvotes: 0

James Kanze
James Kanze

Reputation: 154047

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.

Upvotes: 2

sehe
sehe

Reputation: 394054

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.

Upvotes: 3

Related Questions