使用成员函数管理map STL

// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
using namespace std;
typedef map<int, string> MAPINTSTRING;


int _tmain(int argc, _TCHAR* argv[])
{
	MAPINTSTRING mapTeacher;
	// 插入元素方法1
	mapTeacher.insert(pair<int, string>(1, "Jinxing"));
	// 插入元素方法2
	mapTeacher.insert(MAPINTSTRING::value_type(3, "Sean"));
	pair<MAPINTSTRING::iterator, bool>insert_pair; 
	// 判断insert语句是否成功
	insert_pair = mapTeacher.insert(MAPINTSTRING::value_type(5, "Sean3"));
	if (insert_pair.second == true)
	{
		cout << "Insert Successfully" << endl;
	}
	else
	{
		cout << "Insert Failure" << endl;
	}
	// 插入元素方法3
	mapTeacher[5] = "Yerasel";
	
	// 利用下标遍历
	//int nSize = mapTeacher.size();
	//for (int nIndex = 0; nIndex < nSize; nIndex++)
	//	cout << nIndex << " " << mapTeacher[nIndex] << endl;
	// 如果利用下标遍历会出现mapTeacher	[5]((0,""),(1,"Jinxing"),(2,""),(3,"Sean"),(5,"Yerasel"))

	// 利用迭代器遍历
	MAPINTSTRING::iterator iter;
	for (iter = mapTeacher.begin(); iter != mapTeacher.end(); iter++)
	{
		cout << iter->first << " " << iter->second << endl;
	}
	/*
	1 Jinxing
	3 Sean
	5 Yerasel
	*/

	// 判定数据是否出现
	iter = mapTeacher.lower_bound(2);	// sean
	cout << iter->second << endl;
	iter = mapTeacher.lower_bound(3);	// sean
	cout << iter->second << endl;
	iter = mapTeacher.upper_bound(2);	// sean
	cout << iter->second << endl;
	iter = mapTeacher.upper_bound(3);	// Yerasel
	cout << iter->second << endl;

	pair<MAPINTSTRING::iterator, MAPINTSTRING::iterator>mapPair;
	mapPair = mapTeacher.equal_range(2);
	if (mapPair.first == mapPair.second)
	{
		cout << "Do not Find" << endl;	// Yes
	}
	else
		cout << "Find" << endl;

	mapPair = mapTeacher.equal_range(3);
	if (mapPair.first == mapPair.second)
	{
		cout << "Do not Find" << endl;
	}
	else
		cout << "Find" << endl;			// Yes

	// 删除元素
	int res = mapTeacher.erase(2);	// 或者iter = mapTeacher.find(2); mapTeacher.erase(iter);
	if (res == 0)
	{
		cout << "erase failure" << endl;
	}

	// 清空
	if (!mapTeacher.empty())
	{
		//mapTeacher.erase(mapTeacher.begin(), mapTeacher.end());
		mapTeacher.clear();
	}
	if (mapTeacher.empty())
	{
		cout << "Empty" << endl;
	}


	return 0;
}

试验程序而已


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值