Home > Mobile >  How do I loop through a unordered_map in C without auto?
How do I loop through a unordered_map in C without auto?

Time:08-29

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?

CodePudding user response:

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<int, int> in the range-based for loop as shown below:

//---------vvvvvvvvvvvvvvvvvvv--------------------->not using auto here as you want
for (const std::pair<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

CodePudding user response:

your question is missing a lot of information and literarily , if you searched on web , you would find many ways to loop over unordered_map in C , but anyways , here is the edited version of your code with a test case:

#include <iostream>
#include <unordered_map>
using namespace std;

int main() {

    const int N = 10;
    int arr[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    bool x = true;

    unordered_map<int, int> mp;
    unordered_map<int, int>:: iterator it;
    for (int i = 0; i < N; i  )
    {
        mp[arr[i]]  ;
    }
    mp[9] = 5;
    for (it = mp.begin(); it != mp.end(); it  ) {
        cout << "key is " << it->first << " ,value is " <<  it->second << " " << endl;
        if (it -> second > 2) {
            cout << "WRONG";
            x = false;
            cout << "key is " << it->first << " ,value is " << it->second << " is greater than 2" << endl;
            break;
        }
    }


    return 0;
}
  •  Tags:  
  • c
  • Related