我有一个包含数据的二维 vector ,如果元素/ block 不需要考虑(基于谓词函数),我需要删除它们。这是函数:
bool thresholdNegative (vector<double> val)
{
//short threshold = 10000;
double meansquare = sqrt ( ( std::inner_product( val.begin(), val.end(), val.begin(), 0 ))/(double)val.size() );
if(meansquare < 0)
{
return true;
}else{
return false;
}
}
我使用以下内容:
std::remove_if(std::begin(d), std::end(d), thresholdNegative);
其中 d
是包含所有数据的二维 vector 。
问题是:它似乎没有从 block 中删除任何信息,即使 thresholdNegative
函数确实返回 true。
有什么想法吗?
最佳答案
这就是 remove_if
的工作原理。它实际上并没有从容器中移除任何东西(它怎么可能,它只得到两个迭代器?),而只是重新排序元素,以便那些应该留在容器中的元素聚集在容器的开头。然后该函数返回一个迭代器到容器的新末端,您可以使用它来实际删除元素。
d.erase( std::remove_if(begin(d), end(d), threshold_negative), end(d) );
上面一行使用了所谓的Erase-remove idiom。 .
关于C++ 使用 std::remove_if 删除二维 vector 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18802604/