count()与count_if()

语法: 

#include <algorithm>
//1) 
count( InputItIterator first, InputItIterator last, const T &value );
//2) 
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);

(1) 计数等于 value 的元素。

(2)按条件统计元素个数,返回范围内满足条件的元素数,(即计数谓词 pred 对其返回 true 的元素)。

参数:

first,last要检验的元素范围,代表迭代器的初始和最终位置。使用的范围是[first,last),它包含first和last之间的所有元素,包括first指向的元素,但不包含last指向的元素。
value要搜索的值 
pred一元谓词。接受范围内的元素作为参数,并返回bool类型的值。返回的值表示函数是否对此元素进行计数。
该功能不得修改其参数。这可以是一个函数指针或一个函数对象。

此函数模板的行为等效于:

①count():

template <class InputItIterator, class T>
    typename iterator_traits<InputIt>::difference_type
count(InputItIterator first, InputItIterator last, const T &value)
{
    typename iterator_traits<InputIt>::difference_type ret = 0;
    for (; first != last; ++first)
    {
        if (*first == value)
        {
            ret++;
        }
    }
    return ret;
}

②count_if():

template <class InputItIterator, class UnaryPredicate>
    typename iterator_traits<InputIt>::difference_type
count_if(InputItIterator first, InputItIterator last, UnaryPredicate p)
{
    typename iterator_traits<InputIt>::difference_type ret = 0;
    for (; first != last; ++first)
    {
        if (p(*first))
        {
            ret++;
        }
    }
    return ret;
}

示例:

①count():

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // counting elements in array:
    int myints[] = {10, 20, 30, 30, 20, 10, 10, 20}; // 8 elements
    int mycount = count(myints, myints + 8, 10);
    cout << "10 appears " << mycount << " times.\n";

    // counting elements in container:
    vector<int> myvector(myints, myints + 8);
    mycount = std::count(myvector.begin(), myvector.end(), 20);
    cout << "20 appears " << mycount << " times.\n";

    system("pause");
    return 0;
}
/*输出
10 appears 3 times.
20 appears 3 times.
*/

②count_if():

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

bool IsOdd(int i)
{
    return i % 2 == 1;
}

int main()
{
    vector<int> myvector;
    for (int i = 1; i < 10; i++)
        myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9

    int mycount = count_if(myvector.begin(), myvector.end(), IsOdd);
    cout << "myvector contains " << mycount << " odd values.\n";
    
    mycount = count_if(myvector.begin(), myvector.end(), [](int i) { return i % 3 == 0; });
    cout << "myvector contains " << mycount << " Number divided by 3.\n";

    system("pause");
    return 0;
}
/*输出
myvector contains 5 odd values.
myvector contains 3 Number divided by 3.
*/

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值