Question

I want to create a function/functor which counts the occurences of an letter in an vector of strings.

For example: Output:
Strings: one two three four five
Letter: e
Frequencies: 1 0 2 0 1

I think my algorithm would work (i have to solve it by using functors, count_if and for_each) but I can't put the solution of count_if or for_each/my function LetterFrequency at the cout-Output.

I've already tried by using difference_type of string,...

Hope you can help me - Thank you a lot!

#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;
        };
    };
Was it helpful?

Solution

The line

string::difference_type i = LetterFrequency(mSample);

Constructs a LetterFrequency object and attempts to assign it to a string::difference_type variable (which is probably size_t). As you would expect this doesn't work since there's no valid conversion between those types. It's the operator()(const string& str) function that returns the actual count, not the constructor, so you need to call that function:

LetterFrequency lf(mSample);
string::difference_type i = lf(str);
// Or on one line:
// string::difference_type i = LetterFrequence(mSample)(str);

As an aside, I recommend you turn on compiler warnings (the -Wall flag in g++). This would have helped alert you to the problem by warning you that the parameter str was unused.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top