This code is a slight modification of code here: Given a string array, return all groups of strings that are anagrams
I have spent last 1 hour reading references of map, set and other articles but still can't understand it.
#include <map>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main(){
int n; cin >>n;
string word;
map<string, set<string> > anagrams;
for (int i=0;i<n;i++){
cin >> word;
string sortedWord(word);
sort(sortedWord.begin(), sortedWord.end());
anagrams[sortedWord].insert(word);
}
for (auto& pair : anagrams){
for (auto& word: pair.second){
cout << word << " ";
}
//cout << "\n";
}
}
As I understand set is more of less an ordered vector. So when we come to this line of code
anagrams[sortedWord].insert(word);
It uses our sortedWord as a key and insert the pair into anagrams. Now as I keep on inserting pairs, anagrams is automatically sorted on the basis of sortedWord. So for example, if I insert cat, god , act in this order, anagrams will contain:
act act
act cat
dgo god
Now when I use range based loops, it prints second item of this pair. Is my understanding correct? I have two questions. When we use sortedWord as keys, why doesn't it replace the earlier value? For eg., act cat should replace act act. Is this because of implementation of map or set? And second question, when I try to print pair.first for following input, I get some random output:
Input:
5
cat act dog tac god
Output(for pair.second):
act cat tac dog god
Output(for pair.first):
a c t d g o
Also I would be grateful if someone could give me further uses of set.