samedi 5 mars 2022

unordered_map::find not working for strings

The following piece of code is means to make a dictionary (using an unordered_map), make keys for the dictionary (out of words from wordlist), and add anagrams (of each key) from wordlist in the vector corresponding to the key. The function then returns the vector corresponding to parameter word (which is the vector containing all anagrams of word).

vector<string> anagram(string word, vector<string> wordlist)
{
    unordered_map<string, vector<string>> map;
    
    for (int i = 0; i < wordlist.size(); i++)
    {
        string temp = wordlist[i];
        sort(temp.begin(), temp.end());
        
        if (map.find(temp) != map.end())
        {
            map.find(temp) -> second.push_back(wordlist[i]);
        }
        else
        {
            vector<string> vect;
            map.insert(make_pair(temp, vect));
            //seg-faulting at the following line
            map.find(temp) -> second.push_back(wordlist[i]);
        }
        
        if (map.find(word) != map.end())
            cout << map.find(word) -> first << endl;
    }
    
    return map.find(word) -> second;
}

The input list wordlist is basically a vector of length ~170,000 containing two-letter all the way to twenty-eight-letter English words. I believe the problem is the unordered_map::find function; however, I can't seem to figure out what the problem is.

Aucun commentaire:

Enregistrer un commentaire