开发者

std::list fixed size

How can I create 开发者_StackOverflowstd::list with a fixed element count?


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.


#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.


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜