53STL_map&multimap
基本概念示例代码
基本概念
map & multimap 即 映射 与 多映射(也被称为字典) 用来保存键-值对数据 二者的区别是 键不允许重复 & 键允许重复
基本操作:
insert() 4种方法 (multimap不能使用下标插入数据!)count() 和 find() (find不能修改数据)erase() 3种方法
示例代码
#include <iostream>
#include <map>
#include <string>
using namespace std
;
int main()
{
map
<int, string
> a
;
map
<string
, int> grade
;
multimap
<int, string
> ma
;
a
.insert(map
<int, string
>::value_type(1, "One"));
a
.insert(map
<int, string
>::value_type(2, "Two"));
a
.insert(map
<int, string
>::value_type(3, "Three"));
a
.insert(make_pair(-1, "Minus One"));
a
.insert(pair
<int, string
>(1000, "One thousand"));
a
[1000000] = "One Million";
grade
.insert(make_pair("张飞", 99));
grade
.insert(make_pair("刘备", 56));
grade
["关羽"] = 87;
cout
<< "最简单的查找:" << endl
;
cout
<< a
[3] << endl
;
cout
<< grade
["刘备"] << endl
;
cout
<< "map里一共有" << a
.size() << "个key_value对数据" << endl
;
cout
<< "这些数据是:" << endl
;
map
<int, string
>::const_iterator i
;
for(i
= a
.begin(); i
!= a
.end(); ++i
)
{
cout
<< "Key:" << i
->first
;
cout
<< " Value: " << i
->second
.c_str() << endl
;
}
ma
.insert(multimap
<int, string
>::value_type(3, "Three"));
ma
.insert(multimap
<int, string
>::value_type(45, "Forty Five"));
ma
.insert(make_pair(-1, "Minus One"));
ma
.insert(pair
<int, string
>(1000, "One thousand"));
ma
.insert(pair
<int, string
>(1000, "One thousand"));
cout
<< endl
<< "multimap里有" << ma
.size() << "个数据" << endl
;
multimap
<int, string
>::const_iterator i2
;
for(i2
= ma
.begin(); i2
!= ma
.end(); ++i2
)
{
cout
<< "Key:" << i2
->first
;
cout
<< " Value: " << i2
->second
.c_str() << endl
;
}
cout
<< endl
<< "multimap里有" << ma
.count(1000) << "个1000" << endl
;
multimap
<int, string
>::const_iterator fi
;
fi
= ma
.find(45);
if(fi
!= ma
.end())
{
cout
<< "找到了:" << fi
->first
<< " = " << fi
->second
.c_str() << endl
;
}
else
{
cout
<< "没找到!" << endl
;
}
fi
= ma
.find(1000);
if(fi
!= ma
.end())
{
cout
<< "找到了1000!" << endl
;
size_t n
= ma
.count(1000);
for(size_t i
= 0; i
< n
; ++i
)
{
cout
<< "\t Key: " << fi
->first
;
cout
<< ", Value [" << i
<< "] = " << fi
->second
.c_str() << endl
;
++fi
;
}
}
else
{
cout
<< "没找到1000!" << endl
;
}
if(ma
.erase(-1) > 0)
cout
<< endl
<< "删除-1成功!" << endl
;
multimap
<int, string
>::iterator iElementFound
= ma
.find(45);
if(iElementFound
!= ma
.end())
{
ma
.erase(iElementFound
);
cout
<< "删除45成功!" << endl
;
}
ma
.erase(ma
.lower_bound(1000), ma
.upper_bound(1000));
return 0;
}