Erasing items from an STL list

前端 未结 6 1852
北恋
北恋 2021-02-02 13:21

I want to make a function which moves items from one STL list to another if they match a certain condition.

This code is not the way to do it. The iterator will most lik

6条回答
  •  暖寄归人
    2021-02-02 13:38

    STL lists have an interesting feature: the splice() method lets you destructively move elements from one list to another.

    splice() operates in constant time, and doesn't copy the elements or perform any free store allocations/deallocations. Note that both lists must be of the same type, and they must be separate list instances (not two references to the same list).

    Here's an example of how you could use splice():

    for(std::list::iterator it = myList.begin(); it != myList.end(); ) {
        if(myCondition(*it)) {
            std::list::iterator oldIt = it++;
            myOtherList.splice(myOtherList.end(), myList, oldIt);
        } else {
            ++it;
        }
    }
    

提交回复
热议问题