Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ) {
    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 exactly like the python <3

share|improve this question

migrated from Jun 4 '12 at 13:33

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

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

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 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: – moooeeeep Jun 4 '12 at 11:00
@moooeeeep Many thanks! – BUCKSHOT Jun 4 '12 at 11:43

Your Answer


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.