Problem with Iterator Map C ++ [duplicate]

0

The program for a URI exercise hangs (as in infinite loop) when the input (double) is different from an integer or a decimal number that is not something with a middle (eg 55.5). I have tried to modify the code in several ways, but it seems that the problem is in the second iteration (it2), because without this piece of code it works with any decimal. The strange thing is that with the code the way it is, it locks exactly after reading the double, at the beginning of the code.

The purpose of the exercise is to pass the input value down to the smallest possible number of banknotes and coins.

code:

#include <iostream>
#include <map>
#include <iomanip>

using namespace std;

int main(){

double val=0.0;
map<int,int> nota,moeda;
map<int,int>::reverse_iterator it,it2;

cin >> val;

if(val<0.00 || val>1000000.00)
    return 1;

nota[100]=0;
nota[50]=0;
nota[20]=0;
nota[10]=0;
nota[5]=0;
nota[2]=0;

moeda[100]=0;
moeda[50]=0;
moeda[25]=0;
moeda[10]=0;
moeda[5]=0;
moeda[1]=0;

it=nota.rbegin();

while(val>=2){
    while(val-it->first>=0){
        val-=it->first;
        nota[it->first]++;
    }           
    it++;
}   

it2=moeda.rbegin();

while(val>0){
    while(val-it2->first/100.00>=0){
        val-=it2->first/100.00;
        moeda[it2->first]++;
    }           
    it2++;
}

cout << "NOTAS:" << endl;
for(it=nota.rbegin();it!=nota.rend();it++)
    cout << it->second << " nota(s) de R$ " << fixed << setprecision(2) << it->first/1.0 << endl;
cout << "MOEDAS:" << endl;
for(it2=moeda.rbegin();it2!=moeda.rend();it2++)
    cout << it2->second << " moeda(s) de R$ " << fixed << setprecision(2) << it2->first/100.00 << endl;

return 0;
}
    
asked by anonymous 20.09.2015 / 09:08

1 answer

0

You have not implemented a correct stop rule in both lops while. Try to include a rule that uses iterators because they are the most important ones to be tested, since if they are not pointing to a valid position, an undetermined error situation can occur.
Include this test after each iterator increment, for each case:

if (it == nota.rend()) break;
if (it2 == moeda.rend()) break;
    
20.09.2015 / 16:12