Search code examples
c++unordered-mapstdmapfor-range

How do I loop through a unordered_map in C++ without auto?


I am trying to loop through an unordered_map, to find if any of its VALUES is greater than 2. But this syntax is wrong

unordered_map<int, int> mp;
        
for (int i = 0; i < N; i++)
{
    mp[arr[i]]++;
}

for (int i = 0; i < mp.size(); i++ ) {
    cout << mp[i].second << " " << endl; //mp[i].second is wrong syntax

    if (mp[i].second > 2) {
        cout << "WRONG";
        x = false;
        break;
    }
}

how can I do this?


Solution

  • It seems that you assumed(incorrectly) that mp[i] is std::pair<int, int> when in fact mp[i] gives you the mapped value which is of type int in your example. This can be seen from std::map::operator[]:

    T& operator[]( Key&& key ); (2)
    

    Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

    (emphasis mine)


    Method 1

    Since you don't want to use auto, you can explicitly write the type std::pair<const int, int> in the range-based for loop as shown below:

    //---------vvvvvvvvvvvvvvvvvvvvvvvv--------------------->not using auto here as you want
    for (const std::pair<const int, int> &pair_elem: mp) {
        cout << pair_elem.second << " " << endl; 
        if (pair_elem.second > 2) {
            cout << "WRONG";
            //other code here
        }
    }
    

    Method 2

    Note that you can also use std::find_if instead of a for loop as shown below:

    auto iter = std::find_if(mp.begin(), mp.end(), [](const std::pair<int,int>& elem) 
                                { return elem.second > 2;});
       if (iter != mp.end())
           std::cout << "Greater found ";
       else 
       {
           std::cout<<"Greater not found"<<std::endl;
       }
    

    Demo