map的用法

/*
ACM中map的基本的用法,主要是用数组的形式实现。
1.构造map
2.数据插入
3.map的大小
4.数据的查找
5.数据的删除
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
using namespace std;
int main()
{
    map<int,string>m;//构造map
    m.clear();//数据清空
    m[1] = "abc";//数据插入
    m[2] = "def";
    m[3] = "ghi";
    cout<<m.size()<<endl;//输出map的大小
    if(m[1].size()) cout<<m[1]<<endl;//先判断该数据是否存在,存在就输出
    cout<<m[4].size()<<endl;//不出在输出0
    int  n = m.erase(1);//删除元素,成功的话返回1
    return 0;
}
//如果map的映射值类型为字符类型,那么输出这个映射值不能用printf();输出,会报错,cout就行。
/*
lower_bound(),upper_bound()函数介绍
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include <algorithm>
#include<map>
using namespace std;
int a[10] = {2,3,4,5,6,7,8,9};
int main()
{
    int n = 8;//数组长度
    int pos = lower_bound(a,a+n,5)-a;//返回大于等于5的那个数在数组中的地址
    cout<<a[pos]<<endl;
    pos = upper_bound(a,a+n,5) -a;//返回大于5的那个数在数组中的地址
    cout<<a[pos]<<endl;
    pos = lower_bound(a,a+n,100)-a;//返回的是一个越界的数值,返回8
    cout<<pos<<endl;
    return 0;
}


#include <iostream>
#include <map>
#include <string>
using namespace std;
typedef struct tt//重载排序
{
int id;
string name;
bool operator < (const tt &a) const{
return a.id>id;
}
}; //学生信息
int main()
{
int nSize;
//用学生信息映射分数
map<tt, int>m;
map<tt, int>::iterator iter;
tt s;
s.id = 2;
s.name = "Jack";
m[s] = 100;
s.id = 1;
s.name = "Rose";
m[s] = 100;
for (iter=m.begin(); iter!=m.end(); iter++)
cout<<iter->first.id<<" "<<iter->first.name<<" "<<iter->second<<endl;
}

posted @ 2014-07-25 10:49  SprayT  阅读(152)  评论(0编辑  收藏  举报