是的,你可以这样做。它按原样工作。我提供了一个示例代码并对其进行了解释。
// initialises a vector that holds the numbers from 0-9.
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
print(v);
// removes all elements with the value 5
v.erase( std::remove( v.begin(), v.end(), 5 ), v.end() );
print(v);
在这段代码中,我们想5
从向量中删除,v
然后使用std::remove
and std::erase
。您必须了解它的std::remove
作用。std::remove
交换容器中的元素,以使所有要删除的元素都到最后,并且此函数将迭代器返回到要删除的第一个元素。Nextstd::erase
接受这个迭代器并删除从这个迭代器开始直到容器末尾的所有元素(实际上直到第二个参数。v.end()
在我们的例子中)。
std::vector<int> v1 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> v2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
auto removeIt=std::remove( v1.begin(), v1.end(), [](const int value){
return value==0 || value==3 || value==5;
} );
// now v1 = { 1, 2, 4, 6, 7, 8, 9, 0, 3, 5 } and removeIt points to 0 element (next after 9)..
// removeIt = ^
std::erase(std::remove_if(v2.begin(),v2.end(),[&](const int value){
// remove every object that can be found between removeIt and v1.end()
return std::find(removeIt,v1.end(),value)!=v1.end();
}), v2.end());
// now v2 = { 1, 2, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }
std::erase(removeIt,v1.end());
// now v1 = { 1, 2, 4, 6, 7, 8, 9 }
这段代码完全符合您的需要。