jeudi 23 janvier 2020

Use of "auto" causes deadlysignal, but "auto&" works fine with operator[] of map

I have created a adjacency list using

map<string,priority_queue<string, vector<string>, greater<string>>>& adjList

now when I try to access a value using below method

auto dest = adjList[start];

i get runtime error : "AddressSanitizer:DEADLYSIGNAL"

And if i use

auto& dest = adjList[start];

it works fine and no runtime error.

Please help me understand what is difference.

complete code below

void dfs(string start, map<string,priority_queue<string, vector<string>, greater<string>>>& trips, vector<string>& res)
    {
        auto dest = trips[start];
        while(!dest.empty())
        {
            auto s = dest.top();
            dest.pop();
            dfs(s,trips,res);
        }
        res.push_back(start);
    }


    vector<string> findItinerary(vector<vector<string>>& tickets) {
        vector<string> result;
        map<string,priority_queue<string, vector<string>, greater<string>>> adjList;
        for(auto i : tickets)
        {
            auto it = adjList.find(i[0]);
            if(it == adjList.end())
            {
                adjList[i[0]] = priority_queue<string, vector<string>, greater<string>>();
            }
            adjList[i[0]].push(i[1]);
        }
        vector<string> res;
        dfs("JFK",adjList,res);
        return res;
    }

Aucun commentaire:

Enregistrer un commentaire