cpp的STL之map
map/multimap
map key-value存储,可以理解为关联数组或者字典
multimap 运行一个key存储多个值
使用
//
// main.cpp
// use_stl_map
//
// Created by bikang on 16/10/28.
// Copyright (c) 2016年 bikang. All rights reserved.
//
#include <iostream>
#include <map>
using namespace std;
struct Test{
bool operator ()(const int &a,const int &b) const{
return (a < b);
}
};
void tmap();
int main(int argc, const char * argv[]) {
tmap();
return ;
}
void tmap(){
cout << "test map" << endl;
map<int, string> m1;
multimap<int, string> mm1;
//插入
m1.insert(map<int, string>::value_type(,"a"));
m1.insert(map<int, string>::value_type(,"aa"));
m1.insert(map<int, string>::value_type(,"b"));
m1.insert(map<int, string>::value_type(,"c"));
m1.insert(pair<int, string>(,"dd"));
cout << "m1.size=" << m1.size() << endl;
//访问元素
cout << "m1[1]=" << m1[]<< endl;
//打印
map<int, string>::iterator elem;
for(elem=m1.begin();elem!=m1.end();++elem){
cout << "key:" << elem->first<<",";
cout << "value:" << elem->second;
cout << endl;
}
//查找
elem = m1.find();
if(elem != m1.end()){
cout << elem->first << "=>" << elem->second << endl;
}else{
cout << "find faild" << endl;
}
//删除
//1 通过key删除 2 通过elem删除 3 通过边界删除
m1.erase();
m1.erase(m1.begin());
for(elem=m1.begin();elem!=m1.end();++elem){
cout << "key:" << elem->first<<",";
cout << "value:" << elem->second;
cout << endl;
}
//使用谓词 比较函数
/**
在C++中用到map时,如果KEY是自定义的struct,那么需要自己定义比较函数。因为只有基本类型有默认的比较方法。
定义的方法有两种,一是在作为key的struct中,重载操作符less(<),二是自定义仿函数作为map的比较函数,个人比较喜欢第二种方法。
**/
map<int, int,Test> m11;
m11.insert(pair<int, int>(,));
m11.insert(pair<int, int>(,));
m11.insert(pair<int, int>(,));
m11.insert(pair<int, int>(,));
cout << m11[] << " " << m11[]<<endl;
cout << (m11[] > m11[]) << endl;
}