STL算法 移除.删除(更易型)

转接自STL算法
1. remove() 将区间中等于value的元素移到区间后面(后面元素向前填充)
2. remove_if() remove()满足谓词的元素
3. remove_copy() 将区间的元素value移除copy到另一序列
4. remove_copy_if() 将区间满足谓词的元素remove_copy()
5. unique() 将相邻满足谓词元素移除一个
6. unique_copy() 将相邻元素满足谓词元素删除后序列copy到另一序列

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;
// 1. remove() 将区间中等于value的元素移到区间后面(后面元素向前填充)
// 2. remove_if() remove()满足谓词的元素
// 3. remove_copy() 将区间的元素value移除copy到另一序列
// 4. remove_copy_if() 将区间满足谓词的元素remove_copy()
// 5. unique() 将相邻满足谓词元素移除一个
// 6. unique_copy() 将相邻元素满足谓词元素删除后序列copy到另一序列
void test()
{
    //1
    vector<int> a{ 1,2,3,4,5,6,7,5,5};
    auto pos = remove(a.begin(), a.end(), 5);
    a.erase(pos, a.end());
    for (auto &v : a)
        cout << v << ends;
    cout << endl;
    //2
    vector<int> b{ 1,2,3,4,5,6,7,8,9,0 };
    auto f = [](const int& v)
    {
        return v % 2 == 0;
    };
    auto ip = remove_if(b.begin(), b.end(), f);
    b.erase(ip, b.end());
    for (auto &v : b)
        cout << v << ends;
    cout << endl;
    //3
    vector<int> c;
    remove_copy(a.begin(), a.end(), back_inserter(c), 1);
    for (auto &v : c)
        cout << v << ends;
    cout << endl;
    //4
    vector<int> d{ 1,2,3,4,5,6,7,8,9,0 };
    vector<int> e;
    remove_copy_if(d.begin(), d.end(), back_inserter(e), f);
    for (auto &v : e)
        cout << v << ends;
    cout << endl;
    //5
    vector<int> g{ 1,2,3,4,6,7,8 };
    auto fp = [](const int& a, const int& b)
    {
        return b - a == 2;
    };
    auto gp = unique(g.begin(), g.end(), fp);
    g.erase(gp, g.end());
    for (auto &v : g)
        cout << v << ends;
    cout << endl;
    //6
    vector<int> m{ 1,2,3,4,5,7,9,11 };
    vector<int> n;
    unique_copy(m.begin(), m.end(), back_inserter(n), fp);
    for (auto &v : n)
        cout << v << ends;
}
int main()
{
    test();
    system("pause");
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值