Search code examples
c++vectorerase

Remove elements from two std::vectors based on the first vector's elements


I have to vectors with the same amount of elements. I would like to remove the elements of the first vector based on a condition but I would also like to remove from the second vector the elements that are on the same position.

For example, here are two vectors:

std::vector<std::string> first = {"one", "two", "one", "three"}
std::vector<double> second = {15.18, 14.2, 2.3, 153.3}

And what I want is to remove based on the condition if the element is "one". The final outcome is:

std::vector<std::string> first = {"two", "three"}
std::vector<double> second = {14.2, 153.3}

I can remove the elements from first by using:

bool pred(std::string name) {
  return name == "one";
}

void main() {

  std::vector<std::string> first = {"one", "two", "one", "three"}
  first.erase(first.begin(), first.end(), pred);

}

But I am not aware of a way to remove elements from the second vector as well.


Solution

  • I recommend you change your data structure. Use a structure to hold the two elements:

    struct Entry
    {
      std::string text;
      double      value;
    };
    

    Now this becomes one vector of two elements:
    std::vector<Entry> first_and_second;

    When you search the vector for a given text, you can remove one element containing both text and value.