STL常用算法: distance实现,count_if算法实现,bind2nd的使用..

前面讲到用distance算法来返回两个迭代器之间的距离.下面给出实现:

template <typename T>
int myDistance(T a, T b)
{
    int distance = 0;
    if (a <= b)
    {
        while (a != b)
        {
            distance++;
            a++;
        }
    }
    else
    {
        while (a != b)
        {
            distance--;
            a--;
        }
    }
    return distance;
}

下面我想讲下关于count_if这个算法的使用,一看就知道,这个算法是用来判断满足期望条件的元素的数量的.

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

//这是一个模板函数.
template <typename T>
bool demand(T a)
{
    return (a > 5);
}

int main()
{
    vector<int> s = {2,4,6,1,3,9,7,55,5};

    //STL中的算法,前两个参数基本都是表示范围,count_if统计让第三个参数返回true的元素的数量.
    cout << count_if(s.begin(), s.end(), demand<int>) << endl; //输出4.


    system("pause");
    return 0;
}

当然也会有人说,那我能不能把这个函数的操作放在类中进行呢.这也是可以的,这就相当于仿函数了.这是重载了()操作符.类代码如下:

template <typename T>
class Demand
{
public:
    bool operator()(T a)
    {
        return (a > 5);
    }
};
int main()
{
    vector<int> s = {2,4,6,1,3,9,7,55,5};
    //注意这里的()不要忘记...
    cout << count_if(s.begin(), s.end(), Demand<int>()) << endl;


    system("pause");
    return 0;
}

然而为了统计这些简单的数量,而去写一个函数或者类,实在有些繁琐.所以在STL的配接器中,也有一些已经定义好的函数可以直接使用来完成功能.强烈推荐这种方式!!!

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



int main()
{
    vector<int> s = {2,4,6,1,3,9,7,55,5};

    //只需要这样就可以直接得出结果啦~是不是很神奇呢...原来greater是STL内置的仿函数,而bind2nd是和仿函数配接使用的函数,可以用来进行参数绑定,这里我们绑定了5,所以求的就是大于5的元素个数.
    cout << count_if(s.begin(), s.end(), bind2nd(greater<int>(), 5)) << endl;

    system("pause");
    return 0;
}

以下是count_if的手工实现:
相比之下,lua就不用模板了,直接变量放在参数列表中就好了,,,这就是动态语言和静态语言的不一样…难受啊…

template <typename T, typename C>
int myCount_if(T a, T b, C temp)
{
    int count = 0;
    while (a != b)
    {
        if (temp(*a++))
            count++;
    }
    return count;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值