[C/C++]_[初级]_[使用remove,remove_if,remove_copy_if过滤元素或字符]

场景

  1. 我们经常会过滤掉一个容器里不符合的元素,留下有用的元素. 如果用C++98的写法的话必然得用一个for循环+容器的erase的方法进行匹配,代码量也是挺高的,而且erase方法也有自身的注意事项. 而使用 algorithm 库里的remove,remove_if函数能极大的精简代码.
  2. 对于在界面里添加的简单搜索框, 搜索特定元素时,也可以使用remove_copy_if来提取这些元素,方便简洁.

例子


#include <iostream> 
#include <algorithm>
#include <stdlib.h> 
#include <string.h> 
#include <string>
#include <assert.h>
#include <ctype.h> 
#include <vector> 

using namespace std;  

class A
{

public:
    A():valid_(true){}
    bool valid_;
    int i_;
};


void TestRemove()
{
    std::string str = "adfas\nasdf\n\tasdfa\n";
    std::cout << "[str:" << str << "]"<< std::endl;

    // std::remove
    std::cout << ".............std::remove.........." << std::endl;
    std::string str_remove = str;
    str_remove.erase(std::remove(str_remove.begin(),str_remove.end(),'\n'),str_remove.end());
    std::cout << "[str_remove:" << str_remove << "]"<< std::endl;

    // std::remove_if
    // 移除对象
    std::cout << ".............std::remove_if.........." << std::endl;
    std::vector<A*> arr_removeif;
    for(size_t i = 0; i< 10;++i)
    {
        A* a = new A();
        arr_removeif.push_back(a);
        a->i_ = i;
        if(i%2) a->valid_ = false;
    }

    arr_removeif.erase(std::remove_if(arr_removeif.begin(),
        arr_removeif.end(),[](A* a)->bool{ return !a->valid_;}),
        arr_removeif.end());
    for(auto a: arr_removeif)
    {
        std::cout << a->i_ << std::endl;
        assert(!(a->i_ % 2));
    }

    // 移除字符,可以加 UnaryPredicate 进行过滤.
    std::string str_removeif = str;
    str_removeif.erase(std::remove_if(str_removeif.begin(),str_removeif.end(),
        [](int c)->bool{ return isspace(c & 0xFF);}),
        str_removeif.end());
    std::cout << "str_removeif: " << str_removeif << std::endl;

    // 把需要保留的元素放入另一个容器里,不改变原来的容器.
    std::cout << ".............std::remove_copy_if.........." << std::endl;
    std::cout << "arr_removeif: " << arr_removeif.size() << std::endl;
    std::vector<A*> arr_removecopyif;
    std::remove_copy_if(arr_removeif.begin(),
        arr_removeif.end(),std::back_inserter(arr_removecopyif ),
        [](A* a)->bool{ return !a->valid_;});
    std::cout << "arr_removeif: " << arr_removeif.size() << std::endl;
    std::cout << "arr_removecopyif: " << arr_removecopyif.size() << std::endl;
    //assert(arr_removeif.empty());
    for(auto a: arr_removecopyif)
    {
        std::cout << a->i_ << std::endl;
    }
}

int main(int argc, char const *argv[])  
{  
    TestRemove();
    return 0;  
}  

输出:

[str:adfas
asdf
    asdfa
]
.............std::remove..........
[str_remove:adfasasdf asdfa]
.............std::remove_if..........
0
2
4
6
8
str_removeif: adfasasdfasdfa
.............std::remove_copy_if..........
arr_removeif: 5
arr_removeif: 5
arr_removecopyif: 5
0
2
4
6
8

参考

remove-spaces-from-stdstring-in-c
std::remove, std::remove_if
std::remove_copy, std::remove_copy_if

你可能感兴趣的:(C++,remove,移除元素,remove-if,移除字符)