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>
usingnamespace std;
int numPairs(string pair, string str) {
if (pair.size() != 2){
cout << "The string must be a pair of letters.\n";
return 0;
}
elsereturn 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.
#include <iostream>
#include <string>
#include <algorithm>
usingnamespace 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;
}