Can't we use dot operator?


#1

Can’t we use dot operator(it.second) instead of it->second here? If using that its giving an error but dot operator is used in the other question for example “Two Out of Three”. If anyone knows about this pease help…


#2

It is because when using iterator to an element we need to use arrow operator -> to access the element.
We use dot . operator for direct member selection via object name.

Correct Supporting codes:
(a) Using dot operator

vector<vector<int> > Solution::anagrams(const vector<string> &A) {
    int n=A.size();
    vector<vector<int>>ans;
    unordered_map<string, vector<int>>mp;
    string str;
    for(int i=0; i<A.size(); i++) {
        str=A[i];
        sort(str.begin(), str.end());
        mp[str].push_back(i+1);
    }
    for(auto it:mp) { 
        //here we are trying to access the element from the object directly
        ans.push_back(it.second);
    }
    return ans;
}

(b)Using arrow operator

vector<vector<int> > Solution::anagrams(const vector<string> &A) {
    int n=A.size();
    vector<vector<int>>ans;
    unordered_map<string, vector<int>>mp;
    string str;
    for(int i=0; i<A.size(); i++) {
        str=A[i];
        sort(str.begin(), str.end());
        mp[str].push_back(i+1);
    }
    for(auto it=mp.begin(), it!=mp.end(); ++it) {
        //here we are trying to use iterator to map for accessing the element,
        //that's why we use arrow operator.
        ans.push_back(it->second);
    }
    return ans;
}

I guess this helps!