我想使用remove_if
函数从向量中删除元素,但将擦除限制为 N 个元素。
例子:
// predicate function that determines if a value is an odd number.
bool IsOdd (int i) {
if (we deleted more than deleteLimit)
return false;
return ((i%2)==1);
}
void otherFunc(){
int deleteLimit = 10;
// remove odd numbers:
std::vector<int>::iterator newEnd =
std::remove_if (myints.begin(), myints.end(), IsOdd (how to pass deleteLimit?) );
}
我需要该IsOdd
谓词存储它已删除的元素数量以及我们要删除的元素数量。唯一的方法是使用全局变量吗?像这样:
int deleteLimit = 10;
int removedSoFar = 0;
bool IsOdd (int i) {
if (deleteLimit < removedSoFar)
return false;
if (i%2==1) {
removedSoFar++
return true;
}
return false;
}
remove_if ...