-1

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.

Pey
  • 35
  • 6
  • You could use a `for` loop with indexing, where you will need to use one index for both vectors. This way you erase from both vectors on the same index – Khalil Khalaf Aug 09 '16 at 17:42
  • One way to do this is using zip iterators from Boost - http://stackoverflow.com/a/26659114/241631 – Praetorian Aug 09 '16 at 18:18

2 Answers2

6

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.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
2
for(int i = first.size() - 1; i >= 0; i--){
   if(first[i] == "one"){
       first.erase(first.begin() + i);
       second.erase(second.begin() + i);
   }
}
Amadeusz
  • 1,488
  • 14
  • 21