Search code examples
c++vectorsubtraction

Remove matched elements from 2 different vectors


How can i remove matched elements in c++ while keeping the same order ? i found similar question here but they sort the elements while i want to keep the order for example i have v1{1,2,3,4} , v2{8,6,2,4,3} ,the result should be {1},{8,6}.

here is my code

#include <iostream>
#include<vector>
using namespace std;
int main() {
vector<int> v1{1,2,3,4},v2{8,2,4,3};

  for (auto i=0;i<v1.size();i++){
      for (auto j=0;j<v2.size();j++){
          if (v1[i]==v2[j])
          {
              v1.erase(v1.begin()+i);
              v2.erase(v2.begin()+j);
          }
           
         }
  }
    return 0;
}

but it gives wrong result so how can i get it done?


Solution

  • If you can avoid raw loops, like this

    #include <algorithm>
    #include <iostream>
    #include <vector>
    
    int main() 
    {
    
        std::vector<int> v1{1, 2, 3, 4}, v2{ 8,2,4,3,6 };
    
        auto it1 = std::remove_if(v1.begin(), v1.end(), [&](const int value) { return (std::find(v2.begin(), v2.end(), value) != v2.end()); });
        // don't erase just yet (elements to be deleted will be moved to end, the rest should have preserved their order)
        auto it2 = std::remove_if(v2.begin(), v2.end(), [&](const int value) { return (std::find(v1.begin(), v1.end(), value) != v1.end()); });
    
        v1.erase(it1, v1.end());
        v2.erase(it2, v2.end());
    
        for (const int value : v1) std::cout << value << " ";
        std::cout << "\n";
        for (const int value : v2) std::cout << value << " ";
        std::cout << "\n";
    
        return 0;
    }