您的位置:首页 > 编程语言 > C语言/C++

c++ map 记录

2015-08-11 16:37 239 查看
map
map是一种关系型容器,必须包含两种元素,一个是关键字,另一个是值。map有两种,一种是一般的map对象,它是一对一对应关系;另外一种是multimap,这中类型是可以允许一对多的关系。这两中map类型除此之外没有其他的区别。

头文件: <map>

map的定义:
map <type, type> map对象名
或者是typedef map <type, type> 新的map对象类型名 (这里假设是MyMap)
typedef map<int, string> MyMap;
MyMap myMap;

map的增添操作:(前三种返回的是一个pair <iterator, bool>,不能重复插入相同的值,第四种是直接将原位置的值覆盖)
方法一:
myMap.insert(pair <int, "string">(1, "google1")); 
(1)   my_Map["a"]   =   1; 

myMap.insert(pair<int,
"string">(2, "google2"));
方法二:
myMap.insert(make_pair <int, string> (3,"google3"));
myMap.insert(make_pair <int, string> (4,"google4"));
方法三:
myMap.insert(map <int, string>::value_type(5, "google5"));
myMap.insert(map <int, string>::value_type(6, "google6"));
方法四:
myMap[7] ="google7";

map的遍历:
for (map<int, string>::iterator it = myMap.begin(); it != myMap.end(); ++it){
cout << it->first << " "<< it->second;


map的删除:while(){
map<int, string>::iterator it = myMap.begin();
cout << it->first << " " << it-> second << endl;
myMap.erase(it);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: