STL - 判断式(Predicate) - 单参判断式(Unary Predicate)

Predicate是一种特殊的辅助函数,它会返回Boolean,常常被用来作为排序或者查找准则。

Predicate会有1个或者2个操作数。

 

Unary Predicate(单参判断式)

例子:

我们先写一个算法,如下:

MathUtil.h

#ifndef _Math_Util_H_
#define _Math_Util_H_

using namespace std;

class MathUtil
{
public:
    static bool isPrime(int number);
};

#endif

 

MathUtil.cpp

#include <string>
#include "MathUtil.h"

bool MathUtil::isPrime(int number)
{
    // ignore negative sign
    number = abs(number);

    // 0 and 1 are no prime numbers
    if (number == 0 || number == 1) {
        return false;
    }

    // find divisor that divides without a remainder
    int divisor;
    for (divisor = number / 2; number%divisor != 0; --divisor) {
        ;
    }

    // if no divisor greater than 1 is found, it is a prime number
    return divisor == 1;
}


测试代码

PredicateTest.cpp

#include <list>
#include <algorithm>
#include <iostream>
#include "../../Algorithm/MathUtil.h"
#include "PredicateTest.h"

using namespace std;

void PredicateTest::unaryPredicate()
{
    list<int> coll;
    int startNumber, endNumber;

    cout << "Input Start Number: " << endl;
    cin >> startNumber;
    cout << "Input End Number: " << endl;
    cin >> endNumber;

    // insert elements from start number to end number
    for (int i = startNumber; i <= endNumber; ++i) {
        coll.push_back(i);
    }

    // search for prime number
    auto pos = find_if(coll.cbegin(), coll.cend(),  // range
        MathUtil::isPrime);                    // predicate
    if (pos != coll.end()) {
        // found
        cout << *pos << " is first prime number found" << endl;
    }
    else {
        // not found
        cout << "no prime number found" << endl;
    }
}

void PredicateTest::run()
{
    printStart("unaryPredicate()");
    unaryPredicate();
    printEnd("unaryPredicate()");
}

 

运行结果:

---------------- unaryPredicate(): Run Start ----------------
Input Start Number:
30
Input End Number:
50
31 is first prime number found
---------------- unaryPredicate(): Run End ----------------

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值