C++ MAP 基本用法

/*
map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,
所以在map内部所有的数据都是有序的。

*/
#include <iostream>
#include <map>
using namespace std;
typedef map<int,string> mapStudent;
typedef map<int,string>::iterator mapStudengIter;
typedef pair<int,string> Param;

int main()
{
cout<<"========================"<<endl;
mapStudent mapstudent;
mapStudengIter iter,finditer;
mapstudent[4] = "student_four";
mapstudent.insert(Param(1,"Tongjm"));
mapstudent.insert(Param(2,"Zhaoxp"));
mapstudent.insert(map<int, string>::value_type (3,"student_three"));
mapstudent[10] = "student_ten";
mapstudent[10] = "student_ele";
/*
以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,
用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,
insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值,用程序说明
*/
for(iter = mapstudent.begin();iter!=mapstudent.end();iter++ )
{
cout<< iter->first<<"--->"<<iter->second<<endl;
}
cout<<mapstudent.size()<<endl;
cout<<mapstudent[10]<<endl;
/*
用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,
如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,程序说明
*/
finditer = mapstudent.find(2);
if(finditer!=mapstudent.end())
{
cout<< finditer->first<<"--->"<<finditer->second<<endl;
}
/*
数据的清空与判空
清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map
*/
if((!mapstudent.empty())== true)
cout<<"非空"<<endl;
int n = mapstudent.erase(9);
for(iter = mapstudent.begin();iter!=mapstudent.end();iter++ )
{
cout<< iter->first<<"--->"<<iter->second<<endl;
}
//功能等同于 mapstudent.clear()
mapstudent.erase(mapstudent.begin(),mapstudent.end());
//mapstudent.clear();
if(mapstudent.empty()== true)
cout<<"空"<<endl;

system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值