如何"count_if"字符串的 -STL 函数?
how to cout "count_if"-STL-function of a string?
我想创建一个函数/函子,它计算字符串向量中字母的出现次数。
例如:输出:
字符串:一二三四五
字母:e
频率:1 0 2 0 1
我认为我的算法会工作(我必须通过使用函子,count_if和for_each来解决它),但我不能把count_if或for_each/我的函数LetterFrequency的解决方案放在cout-Output。
我已经尝试过使用difference_type of string,…
希望你能帮助我-非常感谢!
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include "LetterFunctions.h"
using namespace std;
class CompareChar : public unary_function<char, bool>
{
public:
CompareChar(char const s): mSample(s){}
bool operator () (char const a)
{
return (tolower(a) == tolower(mSample));
}
private:
char mSample;
};
class LetterFrequency : public unary_function<string, size_t>
{
public:
LetterFrequency(char const s): mSample(s) {}
size_t operator () (string const& str)
{
return count_if(str.begin(),str.end(),CompareChar(mSample));
}
private:
char mSample;
};
class PrintFrequency : public unary_function<string, void>
{
public:
PrintFrequency(char const s): mSample(s) {}
void operator () (string const& str)
{
string::difference_type i = LetterFrequency(mSample);
cout << i << ", ";
}
private:
char mSample;
};
};
string::difference_type i = LetterFrequency(mSample);
构造一个LetterFrequency
对象并尝试将其赋值给一个string::difference_type
变量(可能是size_t
)。正如您所期望的那样,这不起作用,因为这些类型之间没有有效的转换。返回实际计数的是operator()(const string& str)
函数,而不是构造函数,因此您需要调用该函数:
LetterFrequency lf(mSample);
string::difference_type i = lf(str);
// Or on one line:
// string::difference_type i = LetterFrequence(mSample)(str);
作为题外话,我建议您打开编译器警告(g++中的-Wall
标志)。这将通过警告您参数str
未使用来帮助提醒您注意这个问题。
相关文章:
- 有没有办法捕获 STL 函数未被赋予正确参数的异常?
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 不能对类型化模板使用 STL 函数
- 如何使用 binary_search STL 函数在嵌套类中搜索整数?
- C++ 如何将参数传递给 STL 函数
- STL 函数和函数类型与函数指针类型
- 重载 STL 函数
- 为什么 STL 函数使用节点的颜色来计算 std::map 节点前身
- 我可以期望某些 STL 函数实现是可自动矢量化的吗?
- 指针类型上的 STL 函数对象
- 寻找一种更有效的方法来使用 STL 函数检查字符串是否为回文
- 为什么lambda函数用于stl函数,例如sort(),c 中的max_element()函数以两个参数为输入
- 为什么此 stl 函数调用会导致不正确的布尔计算
- 有没有STL函数可以得到两个C++向量的笛卡尔乘积
- 如何测试 C++ STL 函数的成功或失败(在 Microsoft Visual C++ 6.0 中)
- STL 函数类似于排序
- 无论CRT版本如何,这都是在库中提供STL函数的有效方法吗
- 处理容器的每个成员的stl函数是否可以接受外部参数
- STL函数,用于测试值是否在某个范围内
- 如何"count_if"字符串的 -STL 函数?