I'm getting stuck in a weird infinite loop while using map in c . The first code works good and outputs numbers.
The test cases are:
5 2
1 2 3 4 5
long long N, K, count = 0;
cin>>N>>K;
long long l;
map<long long, long long> mp;
for(int i = 0; i<N; i ){
cin>>l;
mp[l];
}
for(auto a:mp){
cout<<a.first K<<" "<<a.first - K;
}
For the next code I'm getting stuck into an infinite loop, for the same test case, don't know why?
long long N, K, count = 0;
cin>>N>>K;
long long l;
map<long long, long long> mp;
for(int i = 0; i<N; i ){
cin>>l;
mp[l];
}
for(auto a:mp){
cout<<mp[a.first K]<<" "<<mp[a.first - K];
}
The last code keeps on printing 0 till an infinite loop. Any idea why?
CodePudding user response:
The problem is that if the key is not found inside the map, a key-value pair will automatically be created and inserted into the map and so you're changing the size of the map
while iterating it leading to undefined behavior.
Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash.
You can use std::map::at
member function which will throw std::out_of_range
exception when the key is not already inside the map, to confirm that some keys whose corresponding value you're looking for are not inside the map
.
How can I solve this weird error while using map
To solve this make sure, that you don't change the size of the map
while iterating it.
CodePudding user response:
a.first K
might not be a exist key in the map and when you use mp[a.first K]
, it might insert a new key and there is no rules for how the iterator will become.
How can I solve this weird error while using map in c
Check the existence before use it.