zoukankan      html  css  js  c++  java
  • C++之remove和remove_if

    一、Remove()函数

    remove(beg,end,const T& value)  //移除区间{beg,end)中每一个“与value相等”的元素;

      remove只是通过迭代器的指针向前移动来删除,将没有被删除的元素放在链表的前面,并返回一个指向新的超尾值的迭代器。由于remove()函数不是成员,因此不能调整链表的长度。remove()函数并不是真正的删除,要想真正删除元素则可以使用erase()或者resize()函数。用法如下:

    string str1 = "Text with some   spaces";
    str1.erase(std::remove(str1.begin(), str1.end(), ' '),  str1.end());  // "Textwithsomespaces"

    函数原型: 

    template< class ForwardIt, class T >
    ForwardIt remove(ForwardIt first, ForwardIt last, const T& value)
    {
        first = std::find(first, last, value);
        if (first != last)
            for(ForwardIt i = first; ++i != last; )
                if (!(*i == value))
                    *first++ = std::move(*i);
        return first;
    }
    

      

    二、Remove_if()函数

    remove_if(beg, end, op)   //移除区间[beg,end)中每一个“令判断式:op(elem)获得true”的元素;

      remove_if(remove和unique也是相同情况)的参数是迭代器,通过迭代器无法得到容器本身,而要删除容器内的元素只能通过容器的成员函 数来进行,因此remove系列函数无法真正删除元素,只能把要删除的元素移到容器末尾并返回要被删除元素的迭代器,然后通过erase成员函数来真正删除。用法如下:

    bool IsSpace(char x) { return x == ' '; }
    string str2 = "Text with some spaces"; str2.erase(remove_if(str2.begin(), str2.end(), IsSpace), str2.end()); // "Textwithsomespaces"

    函数原型:

    template<class ForwardIt, class UnaryPredicate>
    ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
    {
        first = std::find_if(first, last, p);
        if (first != last)
            for(ForwardIt i = first; ++i != last; )
                if (!p(*i))
                    *first++ = std::move(*i);
        return first;
    }
    

      

  • 相关阅读:
    Windows Phone 7 利用计时器DispatcherTimer创建时钟
    杭电1163 Eddy's digital Roots
    随感1
    杭电 1194 Beat the Spread!
    杭电 1017 A Mathematical Curiosity
    杭电1202 The calculation of GPA
    关于递归的思想
    杭电1197 Specialized FourDigit Numbers
    杭电 1062 Text Reverse
    杭电1196 Lowest Bit
  • 原文地址:https://www.cnblogs.com/cthon/p/9223935.html
Copyright © 2011-2022 走看看