C++ count_if/erase/remove_if 用法详解

每次使用这几个算法时都要去查CPP reference,为了能够加深印象,整理一下基本应用。

cout/cout_if:  return the number of elements satisfying the condition.

count( InputIt first, InputIt last, const T &value );  // counts the elements that are equal to value.

count_if( InputIt first, InputIt last, UnaryPredicate p ); //counts elements for which predicate p returns true.

eg.

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };
 
    // determine how many integers in a std::vector match a target value.
    int target1 = 3;
    int target2 = 5;
    int num_items1 = std::count(v.begin(), v.end(), target1);
    int num_items2 = std::count(v.begin(), v.end(), target2);
    std::cout << "number: " << target1 << " count: " << num_items1 << ' ';
    std::cout << "number: " << target2 << " count: " << num_items2 << ' ';
 
    // use a lambda expression to count elements divisible by 3.
    int num_items3 = std::count_if(v.begin(), v.end(), [](int i){return i % 3 == 0;});
    std::cout << "number divisible by three: " << num_items3 << ' ';
}

remove_if/erase 通常一起用。(使用string的erase成员函数举例)

关于remove_if/remove 移除性算法来说,是根据元素值或某一准则,在一个区间内移除某些元素。这些算法并不能改变元素的数量,它们只是以逻辑上的思考,将原本置于后面的“不移除元素”向前移动,

覆盖那些被移除元素而已,它们都返回新区间的逻辑终点(也就是最后一个“不移除元素”的下一位置)。

ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );// Removes all elements that are equal to value.

ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p );//Removes all elements for which predicate p returns true.

  • 返回的是变动后的序列的新逻辑终点,也就是最后一个未被移除的元素的下一个位置。
  • 未被移除的元素在相对次序上保持不变。
  • 调用者在调用此算法之后,应保证从此采用返回的新逻辑终点,而不再使用原始终点end;

eg.

#include <algorithm>
#include <string>
#include <iostream>
#include <cctype>
 
int main()
{
    std::string str1 = "Text with some   spaces";
    str1.erase(std::remove(str1.begin(), str1.end(), ' '),
               str1.end());
    std::cout << str1 << ' ';
 
    std::string str2 = "Text with some   whitespaces ";
    str2.erase(std::remove_if(str2.begin(),
                              str2.end(),
                              [](char x){return std::isspace(x);}),
               str2.end());
    std::cout << str2 << ' ';
}

此例中使用的是

iterator erase( iterator first, iterator last );//remove_if 返回的是序列的新逻辑终点,然后到序列的最后,这样就把满足条件的都删除了。
原文地址:https://www.cnblogs.com/hipposinsilt/p/6378409.html