anagrams[sig1]
will return a reference to a vector<string>
. Rather than assign to it, you just want to push_back
onto it.
sig1 = signature(w1);
anagrams[sig1].push_back(w1);
As your code is written right now, it's trying to replace the vector instead of add to it. For example, let's assume your input contains both was
and saw
, and that your signature
sorts the letters of the string.
What you want for this case is:
- read "was"
- sort to get "asw"
- insert "was" to get:
anagrams["asw"] -> ["was"]
- read "saw"
- Sort to get "asw" (again)
- insert "saw" to get:
anagrams["asw"] -> ["was", "saw"]
With the code as you've tried to write it, however, in step 6, instead of adding to the existing vector, you'd overwrite the current vector with a new one containing only "saw", so the result would be just anagrams["asw"] -> ["saw"]
.
As far as printmap
goes: the items in the map aren't std::string
s, they're std::pair<std::string, std::vector<std::string>>
, so when you try to do:
void printMap(const map& m)
{
for(string s : m)
...that clearly can't work. I'd usually use:
for (auto s : m)
...which makes it easy to get at least that much to compile. To do anything useful with the s
, however, you're going to need to realize that it's a pair
, so you'll have to work with s.first
and s.second
(and s.first
will be a string
, and s.second
will be a std::vector<std::string>
). To print them out, you'll probably want to print s.first
, then some separator, then walk though the items in s.second
.