c++visual-c++-2010stdlist

Get first N elements of std::list?


What is the correct and safe way to get a new list that is the first N elements of a std::list or the entire list if N >= the list size (and handles N = 0 as well)?

Update

In fact I don't necessarily need a new list, I just want to operate on the subset of the list in subsequent code. I assume creating a new list is a reasonable way to do this (note list size will typically be under 50).


Solution

  • std::list<int> a;
    size_t n = 13;
    auto end = std::next(a.begin(), std::min(n, a.size()));
    

    Make a new list containing the first n elements of the first list:

    std::list<int> b(a.begin(), end);
    

    Or populate an existing list:

    std::list<int> b;
    std::copy(a.begin(), end, std::back_inserter(b));