我想创建一个函数/仿函数来计算字符串向量中字母的出现次数。
例如: 输出:
字符串:一二三四五
字母:e
频率:1 0 2 0 1
我认为我的算法会起作用(我必须使用函子、count_if 和 for_each 来解决它)但我不能将 count_if 或 for_each/我的函数 LetterFrequency 的解决方案放在 cout-Output 中。
我已经尝试过使用不同的字符串类型,...
希望你能帮助我 - 非常感谢!
#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;
};
};