Why is count_if giving me the total of texts

74 Views Asked by At

I was testing the following code, and a bit perplexed as to why count_if is returning me the total of texts?

Match function that takes string of Text as argument and returns true is the Text size is 4

bool Match(string Text)
{
    if (Text.size() == 4)
        return true;
}

numMatchwes produces the total number of Text in a vector

int numMatches(vector<string>Texts, bool (*Match)(string Text))  // Texts is an array
{
    int count = 0;

    for (int i = 0; i < Texts.size(); i++)
    {
    if (Match(Texts[i]) == 1) 

// checking every string in vector and returns true
        count++;
    }

    return count;
}

The main function

int main()
{
    vector<string> texts;

    texts.push_back("Bing");
    texts.push_back("Pony");
    texts.push_back("Mil");
    texts.push_back("Sillty");
    texts.push_back("Ballz");
    texts.push_back("Mars");


   cout << Match("Sind") << endl;

cout << "Matches are: " << numMatches(texts, Match) << endl;

    cout << endl;

    int num = count_if(texts.begin(), texts.end(), Match); // count_if is STL function
 
    cout << num << endl;
}

Now I’m confused as to why count_if is giving me the total of texts?

1

There are 1 best solutions below

1
On

The function Match has undefined behavior in case when the passed string does not have a length equal to 4.

Define it the following way

bool Match( const std::string &Text )
{
    return Text.size() == 4;
}

Correspondingly the function numMatches can be defined the following way

auto numMatches( const std::vector<std::string> &Texts, bool Match(const std::string & ) )
{
    std::vector<std::string>::size_type count = 0;

    for ( const auto &s : Texts )
    {
        if ( Match( s ) ) ++count;
    }

    return count;
}

Here is your updated program.

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

auto numMatches( const std::vector<std::string> &Texts, bool Match(const std::string & ) )
{
    std::vector<std::string>::size_type count = 0;

    for ( const auto &s : Texts )
    {
        if ( Match( s ) ) ++count;
    }

    return count;
}

bool Match( const std::string &Text )
{
    return Text.size() == 4;
}


int main() 
{
    std::vector<std::string> texts;

    texts.push_back( "Bing" );
    texts.push_back( "Pony" );
    texts.push_back( "Mil" );
    texts.push_back( "Sillty" );
    texts.push_back( "Ballz" );
    texts.push_back( "Mars" );


    std::cout << std::boolalpha << Match( "Sind" ) << '\n';
   
    std::cout << "Matches are: " << numMatches( texts, Match ) << '\n';

    std::cout << '\n';

    auto num = std::count_if( std::begin( texts ), std::end( texts ), Match );
 
    std::cout << num << std::endl;
    
    return 0;
}

The program output is

true
Matches are: 3

3