1

I am trying to find out number of occurrences of each element in string. for example string str="aabacdbccdd". a=3, b=2, c=3, d=3.

I am getting error at below loop. Constraints and l are strings.

for (int i = 0; i < constraints.size(); i++)
{
    size_t mycount = std::count(l.begin(), l.end(), constraints[i]);                    
}

Error is: No operator found which takes a left-hand of operand of type 'char'

Could you please help what is the error over here.

Thanks.

sergej
  • 17,147
  • 6
  • 52
  • 89
user3022426
  • 49
  • 2
  • 8
  • You can have a look at [this post](http://stackoverflow.com/questions/13213422/count-the-number-of-occurrences-of-each-letter-in-string). – S.Clem Oct 11 '15 at 17:37
  • I cannot reproduce this error. Which of these lines is the error message referring to? – Beta Oct 11 '15 at 18:05
  • 2
    I think the error is somewhere else, put more code before and after this bloc so we can see what is happening – Captain Wise Oct 11 '15 at 18:08

1 Answers1

1

I assume constraints is a container of string.

l.begin() and l.end() are char iterators. You can not compare a char with a string.

change:

constraints[i]

to

constraints[i][0]

Or try something like this:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    const std::string alphabet("abcdefghijklmnopqrstuwxyz");
    std::string l("aabacdbccdd");

    for (const char& c : alphabet) {
        size_t mycount = std::count(l.begin(), l.end(), c);
        std::cout << c << " = " << mycount << std::endl;
    }
}

Output:

a = 3
b = 2
c = 3
d = 3
e = 0
...
sergej
  • 17,147
  • 6
  • 52
  • 89
  • Thanks you very much. constraints[i][0] works here. But roight now I am looking for a fatstest method to calculate numbers of occuranence of each element in a string as my string contsians arnd 2 millions elements. – user3022426 Oct 11 '15 at 20:47
  • @user3022426 Please consider [accepting](http://meta.stackexchange.com/a/5235) and up-voting if it helped. – sergej Oct 12 '15 at 07:00