运行代码:
//map求和accumulate、参数互换
#include"std_lib_facilities.h"
istream& operator>>(istream& is, map<string, int>&mm)
{
string ss="";
int ii=0;
is >> ss;
if(is>>ii)mm[ss] = ii;
return is;
}
template<class T,class A>
ostream& operator<<(ostream& os, map<T, A>& mm)
{
for ( typename map<T, A>::iterator it = mm.begin(); it != mm.end(); it++)
{
os << "( " << it->first << " , " << it->second << " )" << "\n";
}
return os;
}
int& accumulate_map(map<string, int>mm,int& sum)
{
for (map<string, int>::iterator p = mm.begin(); p != mm.end(); p++)
sum += p->second;
return sum;
}
void msi_to_mis(map<string, int>& msi, map<int, string>& mis)
{
for (map<string, int>::iterator p = msi.begin(); p != msi.end(); p++)
{
mis[p->second] = p->first;
}
}
int main()
try
{
map<string, int>msi;
msi["lecture"] = 21;
msi["Max"] = 23;
msi["Jane"] = 24;
msi["Tom"] = 33;
msi["Sun"] = 55;
msi["lecccture"] = 213;
msi["Maddx"] = 233;
msi["Janeee"] = 4;
msi["Tomd"] = 343;
msi["Sude"] = 25;
map<string, int>::iterator p = msi.find("Sun");
msi.erase(p);
cout << msi<<"\n";
int sum = 0;
sum = accumulate_map(msi, sum);
cout << sum<<"\n\n";
map<int, string>mis;
msi_to_mis(msi, mis);
cout << mis<<"\n";
return 0;
}
catch (exception& e) {
cerr << "error:" << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops:unknown exception!\n";
keep_window_open();
return 2;
}
运行结果: