1、map
代码如下:
/* * map_1.cpp * * Created on: 2013年8月6日 * Author: Administrator */ #include <iostream> #include <map> using namespace std; template <typename T> void print(T b , T e,char c = ' '){ while(b!= e){ cout<< *b++<<c; } cout<<endl; } template<typename K , typename V> ostream& operator<<(ostream& o , const pair<K,V>& p){ return o << p.first << ':' << p.second; } int main(){ map<int,string> mis; mis.insert(map<int,string>::value_type(5,"刘诗诗")); mis.insert(pair<int,string>(8,"刘亦菲")); mis.insert(make_pair(4,"章泽天")); mis[3] = "allen"; mis[6] = "黄东东"; mis.insert(make_pair(5,"刘诗诗")); mis.insert(make_pair(5,"zzt")); print(mis.begin(),mis.end()); }
结果如下:
3:allen 4:章泽天 5:刘诗诗 6:黄东东 8:刘亦菲
2、multimap
代码如下:
/* * multimap_1.cpp * * Created on: 2013年8月6日 * Author: Administrator */ #include <iostream> #include <map> #include <string> using namespace std; template<typename T> void print(T b, T e, char c = ' ') { while (b != e) { cout << *b++ << c; } cout << endl; } template <typename K ,typename V> ostream& operator<<(ostream& o , const pair<K,V> p){ return o<<p.first <<' : '<<p.second; } int main() { typedef multimap<string, double> MSD; MSD m; m.insert(MSD::value_type("章泽天", 40000.0)); m.insert(MSD::value_type("章泽天", 41000.0)); m.insert(MSD::value_type("章泽天", 42000.0)); m.insert(MSD::value_type("章泽天", 43000.0)); m.insert(make_pair("刘诗诗", 30000.0)); m.insert(make_pair("刘诗诗", 35000.0)); m.insert(make_pair("刘诗诗", 39000.0)); m.insert(make_pair("刘亦菲", 50000.0)); m.insert(make_pair("刘亦菲", 55000.0)); m.insert(make_pair("刘亦菲", 40000.0)); print(m.begin(),m.end()); MSD::iterator ib = m.begin(),ie; MSD cnt; while(ib != m.end()){ string name = ib->first; ie = m.upper_bound(name); double sum = 0.0; while(ib != ie ){ sum += ib++->second; cnt.insert(make_pair(name,sum*0.03)); } } print(cnt.begin(),cnt.end()); }
3、set
测试数据为:
1@qq.com 1@qq.com 1@qq.com 1@qq.com 1@qq.com 2@qq.com 2@qq.com 2@qq.com 3@qq.com 3@qq.com
结果为:
1@qq.com 2@qq.com 3@qq.com
4、mutilset
代码如下:
/* * mutilset_1.cpp * * Created on: 2013年8月6日 * Author: Administrator */ #include <iostream> #include <set> #include <fstream> using namespace std; template<typename T> void print(T b , T e, char c = ' '){ while(b!=e){ cout<< *b++<<c; } cout<<endl; } int main(){ multiset<string> ss; string s; ifstream fin("test"); if(!fin){ return 1; } while(fin >> s){ ss.insert(s); } print(ss.begin(),ss.end(),'\n'); }
结果如下:
1@qq.com 1@qq.com 1@qq.com 1@qq.com 1@qq.com 2@qq.com 2@qq.com 2@qq.com 3@qq.com 3@qq.com