繁体   English   中英

C ++使用std :: remove_if移除2D向量的元素

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

我有一个包含数据的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) );

上面的行使用了所谓的Erase-remove习惯用法

擦除通过以下方式完成:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM