map用法
来源:互联网 发布:大连中日红软件 编辑:程序博客网 时间:2024/06/04 01:03
一、map的说明
1 头文件
#include <map>
2 定义
map<string, int> my_Map;
或者是typedef map<string, int> MY_MAP;
MY_MAP my_Map;
3 插入数据
(1) my_Map["a"] = 1;
(2) my_Map.insert(map<string, int>::value_type("b",2));
(3) my_Map.insert(pair<string,int>("c",3));
(4) my_Map.insert(make_pair<string,int>("d",4));
4 查找数据和修改数据
(1) int i = my_Map["a"];
my_Map["a"] = i;
(2) map<string, int>::iterator my_Itr;
my_Itr= my_Map.find("b");
int j = my_Itr->second;
my_Itr->second = j;
不过注意,键本身是不能被修改的,除非删除。
5 删除数据
(1) my_Itr= my_Map.find("c");
my_Map.erase(my_Itr);
(2) int a= my_Map.erase("c"); //如果删除了会返回1,否则返回0
还是注意,第一种情况在迭代期间是不能被删除的,道理和foreach时不能删除元素一样。//i=mymap.erase(it); ----->正确
mymap.erase(it); ----->it失效..
6 迭代数据
for (my_Itr=my_Map.begin(); my_Itr!=my_Map.end(); ++my_Itr) {}
7 其它方法
my_Map.size() 返回元素数目
my_Map.empty() 判断是否为空
my_Map.clear() 清空所有元素
可以直接进行赋值和比较:=, >, >=, <, <=, != 等等
更高级的应用查帮助去吧,^_^;
8 map中默认键值从小到大排列
9
it=lower_bound(key):返回map中第一个大于或等于key的迭代器指针
it=upper_bound(key):返回map中第一个大于key的迭代器指针
二/map的举例
要求: 将mymap中itemstruct 的a大于100的项删除
struct itemstruct
{
int a;
char b[20];
};
map<string, itemstruct > mymap.
解答1:
#include <iostream>
#include <ctime>
#include <map>
using namespace std;
typedef struct itemstruct
{
int a;
char b[20];
}itemS;
itemS s[4] = {{102,"what"},
{33, "hello"},
{198,"world"},
{45, "c++"}
};;
int main()
{
map<string, itemS> mymap;
string str[4] = {"1st","2nd","3rd","4th"};
for(int i = 0; i<4; i++)
{
mymap.insert(make_pair(str[i], s[i]));
}
map<string,itemS>::iterator it;
for(it=mymap.begin(); it!=mymap.end(); it++)
{
if(it->second.a >100){
i=mymap.erase(it); ----->正确
mymap.erase(it); ----->it失效..
}
}
- map用法
- map用法
- map用法
- Map用法
- map用法
- Map用法
- map用法
- map用法
- MAP用法
- map用法
- map用法
- map用法
- map 用法
- MAP用法
- map用法
- map用法
- map用法
- map用法
- 调用函数实现数组的打印
- nodejs 脚本获取webservice数据可key值索引
- 字典树模板
- oracle数据库修改字符集
- ceil、floor函数
- map用法
- poj 3295
- PHP常用知识点记录
- 题目1184:二叉树遍历
- aspectjweaver.jar+ aopalliance.jar+mchange-commons-java.jar+cglib.jar官网下载
- 表情键盘demo
- Java之集合框架Map及其他常用类
- 跨线程、进程通信,主线程与子线程通信
- java中标准的build.xml配置文件