Std :: list fixed size

How to create std::listwith a fixed number of elements?

+3
source share
4 answers
#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 would have to wrap it in the facade class to prevent insertion and erasure.

If this is really what you want, you better use a different container instead list, as, as noted in other answers, you will hide the most beneficial features list.

+8
source

If you need a container with a fixed size, you are probably looking std::tr1::array. (Or just std::arrayfor C ++ 0x.)

, , std::list std::array std::vector.

+10

std::list.

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

.

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

.

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

std:: list:: resize - .

+2

, , ?

The user may be using a cache with a limited number of items and an LRU removal policy. In this case, the list is a good collection to use. Each time an item gets access, you connect this item to the front of the list. If you need to insert a new element (to fill the list), you delete the back of the list.

You can also support some kind of element search, but std :: list is the best class to handle LRU.

+1
source

Source: https://habr.com/ru/post/1768993/


All Articles