c++ - 如何计算 "count_if"- 字符串的 STL 函数?

标签 c++ foreach cout countif

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

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

我认为我的算法可行(我必须使用仿函数、count_if 和 for_each 来解决它)但我不能将 count_if 或 for_each/我的函数 LetterFrequency 的解决方案放在 cout-Output 上。

我已经尝试过使用字符串的 difference_type,...

希望你能帮助我 - 非常感谢!

#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 未使用来提醒您注意问题。

关于c++ - 如何计算 "count_if"- 字符串的 STL 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054920/

相关文章:

c++ - 为什么我们需要 C++ 中的 `class`,而 `struct` 可用于实现相同的目的?

c++ - C++中printf的使用

c++ - 为什么这段代码有不同的输出?

c++ - Nginx + fastcgi 多线程

c++ - 更改 ld-linux 位置

java - 将 While 循环更改为 for 循环

php - 比较 foreach 和 checkbox 的值

javascript - 如何在 es6 中将对象值相乘

c++ - 无法填充 C++ 数组,每个索引处只有最后一项

c++ - boost 序列化: ensure data safety over socket transmition