Hm, the code seems to crash in merge_stats function (i marked it red) and i have no idea why? When i enter only one name and value, it's ok, but when i enter more then one name and value it crashes...

Code:

#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
using namespace std;
typedef multiset<double> SubData;
typedef map<string, SubData> Data;
void collect_data(Data &stats)
{
string name;
while(cin >> name) {
double val;
cin >> val;
stats[name].insert(val);
}
}
void print_setstats(SubData const &stats)
{
size_t count = 0;
double sum = 0.0, median;
for(SubData::const_iterator p = stats.begin(); p != stats.end(); p++, count++) {
if(count == (stats.size() - 1) / 2) {
median = *p;
if(stats.size() % 2 == 0) {
SubData::const_iterator q = p;
q++;
median = (median + (*q))/2.0;
}
}
sum += *p;
}
cout << "sum: " << sum
<< ", mean: " << sum/ (double) count
<< ", median: " << median << endl;
}
void merge_stats(SubData &dst, SubData &src)
{
SubData::iterator hint = dst.begin();
for(SubData::iterator p = src.begin(); p != src.end(); p++) {
hint = dst.insert(hint, *p);
src.erase(p);
}
}
void print_stats(Data &stats)
{
SubData global_set;
for(Data::iterator p = stats.begin(); p != stats.end(); p++) {
cout << (*p).first << ": ";
print_setstats((*p).second);
merge_stats(global_set, (*p).second);
}
cout << "Global stats: ";
print_setstats(global_set);
}
int main()
{
Data stats;
collect_data(stats);
print_stats(stats);
return 0;
}