Trouble with function to determine if something is an anagram

  anagram, c++

I was just working on some challenges on codewars. This particular one is about writing a function to determine is two words are anagrams – meaning they contain the same letters, maybe just out of order.

I am very new to C++ so I am probably overlooking something very basic. Here is the code I wrote, when I run it, main tests the anagram function with the two strings "orang" and "apple" and the program outputs 1(true) meaning that its saying those two words are anagrams when they are not. If I try "orange" and "apple", it outputs 0(false) which is correct. Basically, it is just comparing based on the length of the words and not their individual letter counts.

Here is my code:

#include <iostream> 
#include <bits/stdc++.h>

using namespace std; 

bool isAnagram(std::string test, std::string original){
  //your code here
  map<char, int> freqTest;
  map<char, int> freqOrig;
  for(int i = 0; i < test.length(); i++) {
      char c = tolower(test[i]);
      freqTest[c]++;
  }
  for(int i = 0; i < original.length(); i++) {
      char c = tolower(test[i]);
      freqOrig[c]++;
  }
  
  return freqTest == freqOrig;
}


// Main function 
int main() 
{ 
    string str1 = "orang";
    string str2 = "apple";
    cout<<isAnagram(str1, str2)<<endl;
}

Source: Windows Questions C++

LEAVE A COMMENT