如何cout“count_if”-STL-字符串的功能?

时间:2013-06-11 22:29:19

标签: c++ foreach cout countif

我想创建一个函数/函子来计算字符串向量中字母的出现次数。

例如: 输出:
字符串:一二三四五 信:e
频率:1 0 2 0 1

我认为我的算法会起作用(我必须使用仿函数,count_if和for_each来解决它),但是我不能把cout-output中的count_if或for_each / my function LetterFrequency解决方案。

我已经尝试过使用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;
        };
    };

1 个答案:

答案 0 :(得分:1)

该行

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未使用来帮助提醒您。