tags:

views:

156

answers:

4

How can I create std::list with a fixed element count?

+7  A: 
#include <list>

// list with 5 elements, using default constructor
const size_t fixedListSize(5);
std::list<int> mylist(fixedListSize);  

If you want it to always have exactly 5 elements you'd have to wrap it in a facade class to prevent insertion and erasure.

If that is indeed what you want, you'd be better off using a different container instead of list, since as noted in other responses you would be hiding the most advantageous features of list.

Steve Townsend
That's what `const` is for.
Alf P. Steinbach
@Alf P. Steinbach: Not really. Making the list const will disable insertion and deletion, but at the same time it will disable modification of the actual contents of the list.
David Rodríguez - dribeas
Why the cast? There's only one constructor that will match a call with a single integer type argument.
James McNellis
@David: if you wrap it in a facade class then it doesn't matter any more whether it's a `std::list` or what, so that's pretty irrelevant (one wouldn't use `std::list` then). The only way to restrict operations on `std::list` as such, keeping that type which presumably is what matters, is via `const`. Then elements can't be changed, but that's the cost of what the OP asks for.
Alf P. Steinbach
@James - to make the intent explicit. I know it would work without this but given it's a `list<int>` it seemed a little bit clearer.
Steve Townsend
@James - edited code to clarify what I meant to get across
Steve Townsend
+1  A: 

You should use std::list constructor.

explicit list (size_type n, const T& value = T(), const Allocator& = Allocator());

Just specify at time of creation exact count of elements.

std::list<int> someList(20);

You could specify initial value for each element too.

std::list<int> someList(20, int(42));

std::list::resize is the right solution too.

Keynslug
+10  A: 

If you just want a fixed size container, maybe you are looking for std::tr1::array. (Or just std::array for C++0x.)

If you don't insert or remove elements I don't think there is any advantage in using std::list instead of std::array or std::vector.

sth
+1  A: 

I would have to ask you, why you want it to have a fixed number of elements and why use a list?

It could be that the user is implementing a cache with a limited number of elements and an LRU policy of removal. In that case a list is a good collection to use. Any time an element is accessed, you splice that element to the front of the list. If you need to insert a new elemenet (so the list gets full) you pop off the back of the list.

You can also maintain some kind of lookup for the elements but std::list is the best class to handle LRU.

CashCow