I have written a function that determines whether two words are anagrams. Word A is an anagram of word B if you can build word B out of A just by rearranging the letters, e.g.:
lead is anagram of deal
This is my function:
bool is_anagram(std::string const & s1, std::string const & s2)
{
auto check = [](std::string const & x)
{
std::map<char, unsigned> counter;
for(auto const & c : x)
{
auto it = counter.find(c);
if(it == counter.end())
counter[c] = 1;
else
++counter[c];
}
return counter;
};
return check(s1) == check(s2);
}
This works fine, but as the number of words increases (and this function is used several million times within my application), it very soon became a major bottleneck of my application.
Does anyone have an idea of how to speed this function up?
See Question&Answers more detail:os