Why does set.count('a')
output 1
when there are 3
a's?
Program:
bool isAnagram(string s, string t) {
unordered_set<char> set;
for(int i=0; i<s.size(); i++){
set.insert(s[i]);
}
cout << endl << set.count('a') << endl;
return false;
}
Input:
s = 'anagram'
Output:
1
There's only one a
in the set. If you want multiple a
s you need to use a multiset
.
Example:
#include <iostream>
#include <set>
#include <string>
size_t count_char(const std::string& s, char ch) {
// fill the set directly using the strings begin and end iterators
std::multiset<char> set(s.begin(), s.end());
return set.count(ch);
}
int main() {
std::cout << count_char("anagram", 'a') << '\n';
}
Output:
3