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) );
上面的行使用所谓的擦除删除成语。
擦除由以下人员完成:
auto newEnd = std::remove_if(std::begin(d), std::end(d), thresholdNegative);
d.erase(newEnd, end(d));
我强烈建议您阅读一些有关 std::remove_if 的文档
相关文章:
- 删除使用 new 创建的 2D 或 3D 指针
- C++ 删除[] 2D 数组导致堆损坏
- 重新分配2D阵列并删除旧阵列
- C++ 在类中删除动态 2D 数组时不断"Aborted (core dumped)"
- 从2D数组C 中删除单个元素
- 分割故障:从2D矢量中随机删除元素
- 错误在删除动态分配的2D数组期间发生
- 2D-Array 会在存储新元素时删除元素本身
- 2D矢量-通过搜索删除行
- 用“ strcpy”在2D数组中删除(字符)的一行(字符)时是否存在任何错误
- 我什么时候应该使用删除?(在动态创建的2D数组之后未删除的后果)
- C 删除并在2D动态阵列中删除和紧凑的行
- 删除指向 2D 数组的指针
- 删除 2D 矢量行中的元素 - 使用迭代器
- 从C 中的2D集中删除元素
- 在2D向量中找到一个元素,然后将其删除
- 在 C++ 中从 2D 数组中删除值
- 视觉删除对象指针的 2d 矢量C++
- 如何在没有STL的情况下从2d阵列中删除任何未填充的插槽
- c++ 如何解除分配和删除指向对象的指针的 2D 数组