关联矩阵map的demo程序

// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值