+ 1

Question on Maps in STL, Someone please explain, what exactly is happening here.! What is m[str[i]]..?

#include <iostream> #include<map> using namespace std; int main(){ string str = "hello"; map<int,int>m; for(int i=0;i<str.length();i++){ m[str[i]]++; if(m[str[i]]==2){ cout<<str[i]; } } }

1st Sep 2020, 2:18 PM
shrijith
shrijith - avatar
3 Answers
+ 9
It is iterating over string and finding frequency of characters in that string and as soon it get any any character freq = 2 it prints that character and keep on iterating over string. In map<int, int> m, pair.first is of int type so probably ascii value of character is used and pair.second here is current frequency of that character.
1st Sep 2020, 2:30 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 8
m[str[i]]++; is increasing frequency of character str[i] by 1, it executes in every iteration. By default every key which is str[i] in this case is mapped with 0. m[str[i]] == 2 is checking if current character is having frequency of 2 or not, if it has then print that character. You can run below loop after previous loop to print frequency of h,e,l,o in string "hello" : for(auto it:m){ cout<<it.first<<" "<<it.second<<endl; } map<char, int> would be better as you are only associating chatacter with their frequency and that map<int, int> is taking extra space.
1st Sep 2020, 3:09 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 2
Thanks man for helping. It's really nice this platform has someone who atleast responds.
1st Sep 2020, 3:24 PM
shrijith
shrijith - avatar