Search code examples
c++liststdlist

pop_back() return value in std::list?


I am confused with that, that pop_back() std::list method does not have return value, but how can I then get value from some list and store it in another, for example list of ints?

I assume that this is easy, but I am not familiar with C++, I tried to find solution, but maybe here I can get concrete answer about how to do that.


Solution

  • pop_back() returning a reference to the deleted element would not be desirable, as the reference would immediately be to an invalid element. If you'd like to copy construct the last element of a list to another then delete the element from the first list, you can use the below code. If you don't need to delete the element, just omit the call to std::list::pop_back().

    std::list<int> firstList{1, 2, 3, 4, 5, 6};
    std::list<int> secondList{1, 2, 3, 4};
    secondList.push_back(firstList.back()); //the 6 from firstList has now been copied to secondList
    firstList.pop_back(); //the 6 from firstList has now been removed