0

only half of the test cases pass when i traverse through unordered_map, but when i use vector all of them pass, is there any mistake in my code?

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;  cin>>n;
    unordered_map<int,int> mp;
    vector<int> v;  v.reserve(n);
    while(n--)
    {
        int x,y;  cin>>x>>y;
        int h=y+x;
        if(mp[h]==0){ v.push_back(h); }
        mp[h]++;
    }
    int s; cin>>s;  int sa=0;
    for(auto i:mp)
    {
        int j=i.first+s;
        long long u=mp[j]*(i.second);
        sa=sa+u;
    }
    cout<<sa;
}
3
  • And what are you trying to do? BTW, this looks like UB because of default inserted int if(mp[h]==0) Commented Aug 11, 2020 at 12:57
  • 3
    @pptaszni It is value initialized, no UB here. Commented Aug 11, 2020 at 13:01
  • 2
    What the test cases are testing? What is your code expected to do? What is unexpected in your code? Commented Aug 11, 2020 at 13:07

1 Answer 1

1

In this loop:

for(auto i:mp)
{
    int j=i.first+s;
    long long u=mp[j]*(i.second);
    sa=sa+u;
}

you are potentially modifying mp when you do mp[j], in the case that j is not a key in the unordered_map. Modifying a range that you are iterating over in a range-for loop invokes undefined behavior.

You can use find to check if the key j exists and do something else in that case (but not modify the unordered_map).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.