STL count_if() with lambda expression

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

using namespace std;

int main()
{
    vector<string> svec;
    string word;
    while (cin >> word) {
        svec.push_back(word);
    }
    string::size_type sz = 4;
    auto cnt = count_if(svec.begin(), svec.end(),
                        [sz](const string &s){return s.size()>sz;});
    cout << cnt << " words with length greater than " << sz << endl;
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
std::count_if 是 STL 中的一个算法,用于对容器中的元素进行条件统计。它的函数原型如下: ```c++ template <class InputIterator, class Predicate> typename iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last, Predicate pred); ``` 其中,first 和 last 分别表示容器中要进行统计的元素范围,pred 是一个谓词函数,用于对容器中的每个元素进行判断。count_if 函数会遍历容器中的每个元素,对每个元素都调用谓词函数 pred 进行判断,如果返回值为 true,则该元素被认为是符合条件的,计入统计结果。 count_if 函数返回符合条件的元素个数,其类型为 iterator_traits<InputIterator>::difference_type,表示两个迭代器之间的距离,通常是一个整型数。 下面是一个简单的例子,用于说明 std::count_if 算法的用法: ```c++ #include <iostream> #include <vector> #include <algorithm> bool isOdd(int num) { return num % 2 == 1; } int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; // 使用 std::count_if 算法和 isOdd 谓词函数,统计 vec 中奇数的个数 int count = std::count_if(vec.begin(), vec.end(), isOdd); std::cout << "Count: " << count << std::endl; return 0; } ``` 在这个例子中,我们定义了一个谓词函数 isOdd,用于判断一个数是否为奇数。然后,我们使用 std::count_if 算法和 isOdd 谓词函数来统计 vec 容器中奇数的个数。在调用 std::count_if 算法时,需要传入谓词函数 isOdd 作为第三个参数,表示对容器中的每个元素都要调用该函数进行判断。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值