std::list fixed size

那年仲夏 提交于 2019-12-12 14:25:24

问题


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


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/3907607/stdlist-fixed-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!