考虑这个问题:
// 字符串数组中长度大于3的有多少个?
char* c_str[] = {"abc", "dfhso", "237498", "jdwre"};
你可以想到这样办:
#include <cstdio> // strlen
#include <algorithm> // count_if
using namespace std;
bool lengthThan3(const char* c)
{
return strlen(c) > 3;
}
int main()
{
// 字符串数组中长度大于3的有多少个?
char* c_str[] = {"abc", "dfhso", "237498", "jdwre"};
int length = sizeof(c_str) / sizeof(c_str[0]);
int total = count_if(c_str, c_str + length, lengthThan3);
return 0;
}
上面可以得到数组中长度大于3的字符串有3个。
但是现在想求字符串大于4个,5个。。。的呢? 当然不嫌麻烦可以写各个对应的function。
现在要说的是另外两个方法:
1,用函数对象
// 定义类 LengthThan
class LengthThan
{
public:
LengthThan(int length): length_(length) {}
bool operator()(const char* c)
{
return strlen(c) > length_;
}
private:
int length_;
};
int a_len = 3;
int total = count_if(c_str, c_str + length, LengthThan(a_len));
2, 模版传参
template <int t>
bool lengthThan(const char* c)
{
return strlen(c) > t;
}
int a_len = 3;
int total = count_if(c_str, c_str + length, lengthThan<a_len>);