// map_ex.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct Sstudent
{
Sstudent()
{
ID = 0;
name = "";
}
~Sstudent()
{
ID = 0;
name = "";
}
int ID;
string name;
};
int main()
{
map<int, Sstudent> mymap;
map<int, Sstudent>::iterator itor;
pair<map<int, Sstudent>::iterator, bool> ret1;
pair<map<int, Sstudent>::iterator,map<char, int>::iterator> ret;
//插入元素
pair<int, Sstudent> tempPair;
Sstudent tempStudent;
tempStudent.ID = 1;
tempStudent.name = "jiangshan";
//判断插入是否成功
ret1=mymap.insert(pair<int, Sstudent>(1, tempStudent));
if(ret1.second)
{
cout<<"插入成功";
cout<<"Key value:"<<ret1.first->first<<" ID:"<<ret1.first->second.ID<<" name:"<<ret1.first->second.name<<endl;
}
tempStudent.ID = 2;
tempStudent.name = "zhangyan";
tempPair.first = 2;
tempPair.second = tempStudent;
mymap.insert(tempPair);
tempStudent.ID = 3;
tempStudent.name = "zhang";
tempPair.first = 3;
tempPair.second = tempStudent;
mymap.insert(tempPair);
tempStudent.ID = 4;
tempStudent.name = "jiang";
tempPair.first = 4;
tempPair.second = tempStudent;
mymap.insert(tempPair);
//itor = mymap.begin();
//遍历map 输出
for (itor=mymap.begin(); itor!=mymap.end(); itor++)
{
cout<<"Key value:"<<itor->first<<" ID:"<<itor->second.ID<<" name:"<<itor->second.name<<endl;
}
cout<<"尝试.at的索引操作"<<endl;
cout<<mymap.at(3).ID<<" name:"<<mymap.at(3).name<<endl;
cout<<"用at索引不存在的地址试试"<<endl;
try
{
cout<<mymap.at(5).ID<<" name:"<<mymap.at(5).name<<endl;
}
catch(...)
{
cout<<"索引异常"<<endl;
}
//at修改,没有问题
mymap.at(4).name = "shan";
for (itor=mymap.begin(); itor!=mymap.end(); itor++)
{
cout<<"Key value:"<<itor->first<<" ID:"<<itor->second.ID<<" name:"<<itor->second.name<<endl;
}
//查找,修改
cout<<"find查找,修改"<<endl;
auto Item = mymap.find(3);
if (Item != mymap.cend())//查找到
{
Item->second.name = "yan";
}
for (itor=mymap.begin(); itor!=mymap.end(); itor++)
{
cout<<"Key value:"<<itor->first<<" ID:"<<itor->second.ID<<" name:"<<itor->second.name<<endl;
}
//查找,删除
cout<<"find查找,删除"<<endl;
Item = mymap.find(4);
if (Item != mymap.cend())//查找到
{
mymap.erase(Item);
}
for (itor=mymap.begin(); itor!=mymap.end(); itor++)
{
cout<<"Key value:"<<itor->first<<" ID:"<<itor->second.ID<<" name:"<<itor->second.name<<endl;
}
system("pause");
return 0;
}
关联矩阵map的demo程序
最新推荐文章于 2021-03-16 11:18:38 发布