从2个不同的向量中删除匹配的元素[重复]

问题描述 投票:0回答:1

如何在保持相同顺序的同时删除 C++ 中的匹配元素? 我在这里发现了类似的问题,但他们对元素进行排序,而我想保持顺序 例如我有 v1{1,2,3,4} , v2{8,6,2,4,3} ,结果应该是 {1},{8,6}。

这是我的代码

#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;
}

但它给出了错误的结果,那么我该如何完成呢?

c++ vector subtraction
1个回答
0
投票

如果你可以避免原始循环,就像这样

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.