提问人:Farah 提问时间:11/2/2023 更新时间:11/2/2023 访问量:73
从 2 个不同的向量中删除匹配的元素 [复制]
Remove matched elements from 2 different vectors [duplicate]
问:
如何在保持相同顺序的同时删除 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;
}
但它给出了错误的结果,那么我该如何完成呢?
答:
0赞
Pepijn Kramer
11/2/2023
#1
如果你能避免原始循环,像这样
#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;
}
评论
擦除
返回的内容。