Home > Back-end >  How can I pass a map by reference in C ?
How can I pass a map by reference in C ?

Time:10-09

#include<bits/stdc  .h>
#include<map>
using namespace std;
bool greaterThanExists(int i,std::map<int,int>&mpp)
{
    for(auto it:mpp)
    {
        if(it.first>i && it.second>0)
        {   cout<<it.first<<endl<<endl;
            it.second--;
            return true;
        }
    }
    return false;
}

int main()
{   int n;
    cin>>n;
    map<int,int>mpp;
    for(int i=0;i<n;i  )
    {
    int x;
    cin>>x;
    mpp[x]  ;
    }
    int i=0;
    while(greaterThanExists(i,mpp))
    i  ;
    
    // cout<<i<<endl;
    return 0;
}

Question:https://codeforces.com/contest/1165/problem/B

In this question of Codeforces,I am trying to pass a map by its reference in C ,but apparently the changes are not reflected in the map.

CodePudding user response:

That's because you're iterating over copies of each element:

for(auto it:mpp)

it is a copy. You need to iterate over references to elements, not copies. So use this instead:

for (auto& it : mpp)

Always remember that auto will never bind to a reference. Even if the object you assign to an auto variable is a reference, auto will ignore it unless you explicitly write auto&.

CodePudding user response:

Agree with Nikos C here,you want to iterate over references of the map not copies. Here's another way to loop over the map, which may be slightly easier to read:

bool greaterThanExists(int i,std::map<int,int>&mpp)
{
    for(auto& [key,val]:mpp)
    {
        if (key>1 && val>0)
        {
            cout<<key<<endl<<endl;
            val--;
            return true;
        }
    }
    return false;
}
  • Related