C++ 使用 std::remove_if 删除 2D 矢量的元素

C++ Removing elements of 2D vector using std::remove_if

本文关键字:2D 删除 元素 if 使用 std remove C++      更新时间:2023-10-16

我有一个包含数据的 2D 向量,如果元素/块不值得考虑(基于谓词函数),我需要删除它们。这是函数:

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是包含所有数据的 2D 向量。

问题是:它似乎没有从块中删除任何信息,即使函数thresholdNegative确实返回 true。

知道为什么吗?

这就是

remove_if的工作方式。它实际上并没有从容器中删除任何东西(怎么可能,它只得到两个迭代器?),相反,它只是对元素进行重新排序,以便那些应该留在容器中的元素被收集在容器的开头。然后,该函数将迭代器返回到容器的新端,您可以使用该迭代器实际删除元素。

d.erase( std::remove_if(begin(d), end(d), threshold_negative), end(d) );

上面的行使用所谓的擦除删除成语。

擦除由以下人员完成:

auto newEnd = std::remove_if(std::begin(d), std::end(d), thresholdNegative);
d.erase(newEnd, end(d));

我强烈建议您阅读一些有关 std::remove_if 的文档