简体   繁体   中英

std::list fixed size

如何创建具有固定元素数的std::list

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM