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
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;
}
}