Search code examples
c++multimap

I got a identical Key twice in a multimap, it just exists one in the textfile.


i have an issue with multimap. I read a file, that stores Years and Temepratures for everymonth.

2011 9.23 3.23 4.23 and so on.

Now i want to write the average temperature from each year back to a file.

I used a multimap. The double stores my average temps, and from my class Year i call the getYear()Method to get the Year that fits to the average temp.

I need multimap, because there are identical average temps.

But if i look now into the output file, i see that the Year 2011 is twice with the same average temp.

In the input file, the Year 2011 is just written once.

Do i get the same Year twice, because its at the and of the input file? So maybe the issue comes from reading the file in the last line?

This is how the outpuf file looks:

1994 9.7025

2011 9.635

2011 9.635

2002 9.55667

My stringsteam ohneKomma stores the input file.

while(ohneKomma)    
{  
    Year year;
    ohneKomma >> _jahr;
    year.setJahr(_jahr);

    ohneKomma >> _d1;
    ohneKomma >> _d2;
    ohneKomma >> _d3;
     //and so on....

    year.setAvgTemps(_d1, _d2, _d3, _d4, _d5, _d6, _d7, _d8, _d9, _d10, _d11, _d12);

    map2.insert(make_pair(year.getMittelwert(), year));//fallend
    ;
}

I hope you guys can help me and sorry for my bad english but i hope you understand what i mean :)

Thanks


Solution

  • Change your code to check for input success as the while condition:

    while(ohneKomma >> jahr >> _d1 >> d2 ....)    
    {  
        Year year;
        year.setJahr(_jahr);
    
    
        year.setAvgTemps(_d1, _d2, _d3, _d4, _d5, _d6, _d7, _d8, _d9, _d10, _d11, _d12);
    
        map2.insert(make_pair(year.getMittelwert(), year));//fallend
    }