Search code examples
c++stlstdlist

std::list fixed size


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


Solution

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