关于一个如何使用泛型算法的问题
问题是这样的,有两个容器A、B,需要从容器A中删除与容器B重复的元素,用泛型算法 std::remove_if 和 std::find_if 如何实现,求指点,可以以 std::vector<int> 为例。 泛型算法
[解决办法]
this literally does what you have asked for.
#include <algorithm>
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> A {0,1,2,3,4,5,6,7,8,9};
std::vector<int>const B{3,5,8};
std::cout << "before removal" << std::endl;
for (auto const a : A) { std::cout << a << " "; } std::cout << std::endl;
for (auto const b : B) { std::cout << b << " "; } std::cout << std::endl;
A.erase(std::remove_if(A.begin(),A.end(),[&](int const a)
{
return B.end() != std::find(B.begin(),B.end(),a);
}),A.end());
std::cout << "after removal" << std::endl;
for (auto const a : A) { std::cout << a << " "; } std::cout << std::endl;
for (auto const b : B) { std::cout << b << " "; } std::cout << std::endl;
}
but a faster solution would be
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main ()
{
std::vector<int> a {0,1,2,3,4,5,6,7,8,9};
std::vector<int> b{3,5,8};
std::cout << "before removal" << std::endl;
for (auto const a : a) { std::cout << a << " "; } std::cout << std::endl;
for (auto const b : b) { std::cout << b << " "; } std::cout << std::endl;
std::sort(a.begin(),a.end());
std::sort(b.begin(),b.end());
std::vector<int> c;
std::set_difference(a.begin(),a.end(),
b.begin(),b.end(),
std::back_inserter(c));
a = std::move(c);
std::cout << "after removal" << std::endl;
for (auto const a : a) { std::cout << a << " "; } std::cout << std::endl;
for (auto const b : b) { std::cout << b << " "; } std::cout << std::endl;
}