// 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;
}
试验程序而已