c++ arrays and pointers

so how can i get the frequency of an element in an array using pointers?
I assume you want to count how many times a particular value occurs in an array?

Walk the array start to finish and keep a counter of the number of occurrences...
xxx
Last edited on
xxx
Last edited on
fgh
Last edited on
boubounas, i think like this if the variable letter is i.e. "a" it doesnt count if there is an "A" in the string
xxx
Last edited on
yorgo??? NEXT QUESTION PLEASE
It is still possible to do this with count_if (in one line of code, no less), however as this is for a homework assignment, I doubt it will be acceptable that way. Nonetheless, in the name of education, I give an "advanced" solution:

1
2
3
4
5
6
7
8
9
#include <algorithm>
#include <ctype>     
#include <string.h>  
#include <boost/bind.hpp>

int letterfrequency( char s[], char letter ) {
    return std::count_if( s, s + strlen( s ),
        boost::bind( tolower, _1 ) == boost::bind( tolower, letter ) );
}


Or very slightly better performance, but 2 lines


1
2
3
4
5
6
7
8
9
10
#include <algorithm>
#include <ctype>     
#include <string.h>  
#include <boost/bind.hpp>

int letterfrequency( char s[], char letter ) {
    int as_lower_case = tolower( letter );
    return std::count_if( s, s + strlen( s ),
        boost::bind( tolower, _1 ) == as_lower_case );
}

Topic archived. No new replies allowed.