about the interator of map
This is the exercise of TC++PL ch6
(*2) Read a sequence of possibly whitespaceseparated
(name,value) pairs, where the name is a
single whitespaceseparated
word and the value is an integer or a floatingpoint
value. Compute
and print the sum and mean for each name and the sum and mean for all
names. Hint: ?6.1.8.
struct Stat
{
Stat():sum_(0.0),count_(0)
{
}
double sum_;
int count_;
};
using std::string;
using std::cin;
using std::cout;
using std::endl;
typedef std::map<string,Stat> Data;
typedef Data::iterator pData;
void collect_data(Data &stats)
{
string name;
while(cin >> name)
{
if( name == "Quit")
{
return ;
}
float value;
cin >> value;
stats[name].sum_ += value;
++stats[name].count_;
}
}
void print_data(const Data& stats)
{
double sum = 0;
int count = 0;
for(Data::iterator p = stats.begin(); p != stats.end(); ++p)//when
i modify iterator to const_iterator it can work
{
std::cout << (*p).first
<< " sum =" <<(*p).second.sum_
<< ", mean = "
<<(*p).second.sum_/(*p).second.count_
<< endl;
sum += p->second.sum_;
count += p->second.count_;
}
cout << endl;
cout << " Globle sum: " << sum << endl;
cout << " Globle count: " << count << endl;
}
int main()
{
Data stats;
collect_data(stats);
print_data(stats);
return 0;
}
The code will cause compile error, I wonder the reason:
bzhu@TY-PC /g/WorkingDir/tcplex/ch6
$ make
g++ -g -o6.3.exe 6.3.cpp
6.3.cpp: In function `void print_data(const Data&)':
6.3.cpp:39: error: conversion from
`std::_Rb_tree_const_iterator<std::pair<const std::string, Stat> >' to
non-scalar type `std::_Rb_tree_iterator<std::pair<const std::string,
Stat> >' requested
make: *** [6.3.exe] Error 1
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]