linux上练习 c++ 关联式容器地图特性
linux下练习 c++ 关联式容器map特性
/*
map.cpp
map特性 不允许key重复 key/value对 key可以当下标访问value,key不存在则插入新的key/value对,以0初始化 */ #include<iostream> #include<string> #include "print.h" #include<map> using namespace std; typedef pair<int,string> pairmp; #include<map> int main() { map<int,string> mp; mp.insert(pair<int,string>(1,"aaa")); mp.insert(make_pair(5,"bbb"));//自动匹配类型,构造pair mp.insert(map<int,string>::value_type(4,"fff"));//内部类型,也能自动构造相应的pair mp.insert(make_pair(2,"hhh")); mp.insert(make_pair(2,"hhh")); mp[2]="hhh1";//有则修改 mp[3]="ddd";//无则插入 print(mp.begin(),mp.end()); return 0; }
print.h
//print.h #include <iostream> using namespace std; #ifndef print_fun #define print_fun template<typename T> ///显示序列数据 void print(T b,T e,char c=' ') { bool isExit=false; while (b!=e) { cout<<*b++<<c; isExit=true; } if(isExit) cout<<endl; } template<typename K,typename V> ostream& operator<<(ostream& o,const pair<K,V>& p)//重载输出map类型元素 { return o<<p.first<<':'<<p.second; } #endif