假设我有一节课:
class sampleVector
{
public:
int a;
int b;
string c;
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个带有多个sampleVector对象的向量,但是向量有2个(多个)连续的sampleVector对象,它们具有相同的a(例如5)和b(比如10).
现在我想删除矢量中具有= 5和b = 10的所有sampleVector对象.
问题是,对于多次连续发生,下面是一种方法:
for (;it!=itEnd;it++)
{
if (it->getA() == 5 && it->getB() == 10)
{
vec.erase(it);
it=vec.begin(); // Resetting this is must
}
}
Run Code Online (Sandbox Code Playgroud)
但我想知道如何使用"删除",因为以下不起作用:
for (;it!=itEnd;it++)
{
if (it->getA() == 5 && it->getB() == 10)
{
vec2.erase(remove(vec2.begin(), vec2.end(), *it), vec2.end()); // doesn't even compile
}
}
Run Code Online (Sandbox Code Playgroud)
当我们有一个原始数据类型的向量时,我们可以使用这种方法去除,并且我们有一个需要删除的特定值.但是对于非原始数据类型的向量,我们如何通过传递迭代器而不是值来使用"remove"?
您不需要使用循环作为std::remove 文档说明;
从范围[first,last]中删除满足特定条件的所有元素
由于您要删除仅与您的类的一部分匹配的特定项,您应该使用std::remove_if并提供谓词:
template <class ForwardIt,class UnaryPredicate> ForwardIt remove_if(ForwardIt first,ForwardIt last,UnaryPredicate p);
例如:
std::remove_if(std::begin(vec), std::end(vec),
[](sampleVector& v) { return (v.a == 5 && v.b==10); });
Run Code Online (Sandbox Code Playgroud)
然后你可以std::erase像以前一样将它传递给你.