-2

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?

5
  • removing elements does not alter order of remaning ones, hence the question is unclear Commented Nov 2, 2023 at 8:51
  • 3
    Your current code skips elements. If you sit down to think about it a little, perhaps using pen and paper to help, I'm sure you will figure out what's happening and why. Commented Nov 2, 2023 at 8:51
  • what is wrong results? You should include output and expected output in the question. This code has no ouput. Did you use a debugger? Please mention that in the question. Commented Nov 2, 2023 at 8:51
  • 1
    As for a simple way to solve your problem, I recommend you iterate using iterators and use what erase returns. Commented Nov 2, 2023 at 8:52
  • stackoverflow.com/a/8628963/4165552 - like this, but there will be 2 nested loops in your case Commented Nov 2, 2023 at 8:56

1 Answer 1

0

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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.