Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is this a reasonable C++ wrapper function for Python's "list.count([character])" method?

int count( char CHAR, string STR ) {
    int counter = 0;
    for ( int i = 0 ; i < STR.size() - 1 ; i++  ) {
        if ( STR[i] == CHAR ) {
            counter++;
        }
    }
    return counter;
}
//Edited "for( int i = 0 ; i++ < STR.size-1 ;  )" to "for(int i = 0 ; i < STR.size ; i++)" now it counts the first char of the string =D

Tested it...works exactly like the python <3

share|improve this question

migrated from stackoverflow.com Jun 4 '12 at 13:33

This question came from our site for professional and enthusiast programmers.

3  
you seem confused about what a wrapper function is. A wrapper function should call what it is wrapping, not reimplement it. –  Winston Ewert Jun 5 '12 at 5:06

1 Answer 1

When STR is empty, STR.size() returns 0u. As a result, STR.size()-1 becomes maximum value of unsigned size type. i++ < STR.size()-1. This will lead the function to crash.

Also your function will not count CHAR of the first character of STR.

You may want to use standard library.

std::count(begin, end, CHAR) is just what you are looking for.

for example,

#include <algorithm>
#include <string>

...
char CHAR = 'l';
std::string STR("Hello World!");
ptrdiff_t counter = std::count(STR.begin(), STR.end(), CHAR);
...
share|improve this answer
    
Oh...im reading primer C++ n its pretty basic so i never even knew this existed in C++ :( do you have any suggestions on some great books/resources i can use to get myself up and coding in C++ the right way? –  BUCKSHOT Jun 4 '12 at 10:36
    
Oh thanks for pointing that out :) –  BUCKSHOT Jun 4 '12 at 10:44
    
@BUCKSHOT - see this FAQ-entry: stackoverflow.com/q/388242/1025391 –  moooeeeep Jun 4 '12 at 11:00
    
@moooeeeep Many thanks! –  BUCKSHOT Jun 4 '12 at 11:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.