移除型算法是一种特殊的更易型算法,它们可以移除区间内的元素,也可以在复制过程中执行移除动作。
//对于每个测试函数, 导入以下头文件
#include
#include
#include
using namespace std;
int main()
{
vector<int> a{ 1, 2, 4, 4, 5, 4, 8, 10 };
auto it = remove(begin(a), a.end(), 4);
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
cout << endl;
a.erase(it,a.end());
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
int main()
{
vector<int> a{ 1, 2, 4, 4, 5, 4, 8, 10 };
auto it = remove_if(begin(a), a.end(), [](int i) {return i - 4 <= 0; });
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
cout << endl;
a.erase(it,a.end());
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
int main()
{
vector<int> a{ 1, 2, 4, 4, 5, 4, 8, 10 },b;
remove_copy(begin(a), a.end(),back_inserter(b), 4);
for_each(b.begin(), b.end(), [](int i) {cout << i << ' '; });
}
int main()
{
vector<int> a{ 1, 2, 4, 4, 5, 4, 8, 10 },b;
remove_copy_if(begin(a), a.end(),back_inserter(b), [](int i) {return i - 4 <= 0; });
for_each(b.begin(), b.end(), [](int i) {cout << i << ' '; });
}
int main()
{
vector<int> a{ 1, 2, 4, 4, 5, 4, 8, 10 };
auto it = unique(begin(a), a.end()); //返回最终迭代器位置
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
cout << endl;
a.erase(it, a.end());
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; });
}
int main()
{
vector<int> a{ 1, 2, 4, 4, 5, 4, 8, 10 },b;
unique_copy(begin(a), a.end(),back_inserter(b));
for_each(a.begin(), a.end(), [](int i) {cout << i << ' '; }); //copy都不影响原容器
cout << endl;
for_each(b.begin(), b.end(), [](int i) {cout << i << ' '; });
}