您可以使用std::copy_if()
创建容器的子集:
#include <algorithm>
#include <iterator>
#include <list>
std::list<object> myObjectList, anotherMyObjectList;
// fill myObjectList somehow
std::copy_if(cbegin(myObjectList),
cend(myObjectList),
std::back_inserter(anotherMyObjectList),
[](const object& o) { return o.IsSomething(); });
或者如果您使用的是 C++98/03:
#include <algorithm>
#include <iterator>
#include <list>
std::list<object> myObjectList, anotherMyObjectList;
// fill myObjectList somehow
struct is_something {
bool operator()(const object&) {
return object.IsSomething();
}
};
std::copy_if(myObjectList.cbegin()
myObjectList.cend(),
std::back_inserter(anotherMyObjectList),
is_something());