当心变量的初值、缺省值错误,或者精度不够。
1 #include <iostream> 2 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 4 #include <string> 5 #include <map> 6 7 using namespace std; 8 9 //创建multimap的实例,整数(int)映射字符串(string) 10 typedef multimap<int, string> INT2STRING; 11 12 //测试multimap容器 13 14 int main(int argc, char** argv) { 15 //创建multimap对象theMap 16 INT2STRING theMap; 17 INT2STRING::iterator theIterator,it; 18 19 //向theMap容器中添入数据,数字和字符串配对 20 //每个元素是一个映射对 21 theMap.insert(INT2STRING::value_type(90,"张卫")); 22 theMap.insert(INT2STRING::value_type(85,"李华")); 23 theMap.insert(INT2STRING::value_type(73,"赵明")); 24 theMap.insert(INT2STRING::value_type(96,"郝名")); 25 26 //显示multimap容器的所有对象 27 cout<<"theMap.begin()--theMap.end():"<<endl; 28 for (theIterator=theMap.begin();theIterator!=theMap.end();++theIterator){ 29 cout<<(*theIterator).second; 30 cout<<" "<<(*theIterator).first<<endl; 31 } 32 33 //测试multimap容器key的非惟一性 34 theMap.insert(INT2STRING::value_type(90,"李朋")); 35 theMap.insert(INT2STRING::value_type(85,"钱德")); 36 theMap.insert(INT2STRING::value_type(93,"赵刚")); 37 38 //按成绩高低输出multimap容器的所有对象 39 INT2STRING::reverse_iterator i; 40 cout<<"theMap.rbegin()--theMap.rend():"<<endl; 41 for (i=theMap.rbegin();i!=theMap.rend();++i){ 42 cout<<(*i).second; 43 cout<<" "<<(*i).first<<endl; 44 } 45 46 //按关键给定的区间显示序列中的元素 47 cout<<"[theMap.lower_bound(80),theMap.upper_bound(90)] :"<<endl; 48 for (it=theMap.lower_bound(80);it!=theMap.upper_bound(90);it++) { 49 cout<<(*it).second; 50 cout<<" "<<(*it).first<<endl; 51 } 52 53 //显示theMap的状态信息 54 cout<<"theMap.size():"<<theMap.size()<<endl; 55 cout<<"theMap.max_size():"<<theMap.max_size()<<endl; 56 cout<<"theMap.count(90):"<<theMap.count(90)<<endl; 57 58 //清除90分以下的数据,并显示结果 59 theMap.erase(theMap.lower_bound(60),theMap.upper_bound(89)); 60 cout<<"theMap.rbegin()--theMap.rend():"<<endl; 61 for (i=theMap.rbegin();i!=theMap.rend();++i){ 62 cout<<(*i).second; 63 cout<<" "<<(*i).first<<endl; 64 } 65 return 0; 66 }