user1709708
user1709708

Reputation: 1577

How to remove elements of a vector with a predicate based on another vector

I have two vectors

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

and would like to filter out the indices in both vectors where the image is empty. This can easily be done on a single vector:

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

But now I'd like to remove the very same indices on image_paths as well. This can of course be generalized to vectors of arbitrary types or arbitrary predicates. How can I do this most elegantly?

Upvotes: 1

Views: 353

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

Something like this perhaps:

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());

Only works for std::vector, where flat storage is guaranteed.

Upvotes: 1

Related Questions