如何使用基于另一个向量的谓词移除向量的元素

时间:2019-02-27 18:15:36

标签: c++11 vector stl erase

我有两个向量

std::vector<Mat> images;
std::vector<std::string> image_paths;

,并希望过滤出图像为空的两个向量中的索引。这可以很容易地在单个向量上完成:

std::remove_if(images.begin() images.end(), [](const Mat& img) { return img.empty(); });

但是现在我也想删除image_paths上相同的索引。当然,这可以概括为任意类型或任意谓词的向量。我该如何最优雅地做到这一点?

1 个答案:

答案 0 :(得分:1)

可能是这样的:

std::erase(std::remove_if(image_paths.begin(), image_paths.end(),
  [&](const std::string& path) {
    auto index = &path - &image_paths.front();
    return images[index].empty();
  }), image_paths.end());

std::erase(std::remove_if(images.begin(), images.end(),
  [](const Mat& img) { return img.empty(); }), images.end());

仅适用于保证平面存储的std::vector