Problem with count()

closed account (jwC5fSEw)
Having finished my first C++ book, I recently picked up TC++PL. (While much of it's gonna go over my head, I've already learned a lot I didn't know about the language.) I'm trying to solve an exercise in the book using count(). Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int numPairs(string pair, string str) {
    if (pair.size() != 2){
        cout << "The string must be a pair of letters.\n";
        return 0;
    }
    else return count(str.begin(), str.end(), pair);
}

int main() {
    int x = numPairs("ab", "ababcdcdab");
    cout << x;
    return 0;
}


From what I can tell, this should work fine; however, I get an error on line 11 stating that there is no match for operator== in stl_algo.h in count()'s definition. I don't really understand what this has to do with my code.
I'm not 100% sure, but I think that count will look at each element of the string 'str' using a string iterator type, which can't be compared to your string object 'str' (hence the error relating to the '==' operator). See http://www.cplusplus.com/reference/algorithm/count/

How to do what you want using count and iterators? Someone else will have to help us out there, I'm not sure.

He's right. The count() algorithm only looks at individual elements of the container -- in this case that's individual chars in the string.

But you are trying to compare the individual characters with a string (pair), so the compiler is complaining to you. The third argument should be a char:

count(str.begin(), str.end(), 'a'); // number of 'a's in str

I don't think any of the standard algorithms can be easily co-opted to do what you want... You may have to write your own using search() until it returns str.end(). If you can't figure it out later I'll take another look at it.

Hope this helps.
closed account (jwC5fSEw)
Ah, that didn't occur to me. I'll take a stab at it, thanks for the help!

EDIT: That was actually incredibly easy. Here's my solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int numPairs(string pair, string str) {
    if (pair.size() != 2){
        cout << "The string must be a pair of letters.\n";
        return 0;
    }
    else {
        int count = 0;
        for (unsigned i = 0; i < str.size() - 1; ++i)
            if ((pair[0] == str[i]) && (pair[1] == str[i+1])) ++count;
        return count;
    }
}

int main() {
    int x = numPairs("ab", "abcdabdeabab");
    cout << x;
    return 0;
}
Last edited on
Nice!
closed account (jwC5fSEw)
Thanks!
Topic archived. No new replies allowed.