1.关于本文
文中描述的是一个学习Map类过程中写的程序,程序中进行了以下步骤
1)建立map<string, string>
2)为map添加数据(三种方式)
3)根据键搜索出对应值
4)使用迭代器遍历map
5)使用erase函数删除键值对
6)使用clear函数清空map中的键值对,使用size函数查看map大小
2.程序代码
#include <iostream>
#include <map>
using namespace std;
int main()
{
cout << "Program Activate!" << endl << endl;
map<string, string> mapNameList;
// Add Data
cout << "Add Data!" << endl;
// Method [1]
mapNameList.insert(pair<string, string>("101", "Tsybius"));
mapNameList.insert(pair<string, string>("102", "Galatea"));
mapNameList.insert(pair<string, string>("105", "Lepidus"));
mapNameList.insert(pair<string, string>("104", "Octavius"));
mapNameList.insert(pair<string, string>("103", "Antonius"));
// Method [2]
mapNameList.insert(map<string, string> :: value_type("106", "Atia"));
// Method [3]
mapNameList["107"] = "Servilia";
cout << endl;
// Output Values
cout << "Find Keys " << endl;
cout << "102: " << mapNameList["102"] << endl;
cout << "108: " << mapNameList["108"] << endl;
cout << endl;
// Traverse Map
cout << "Traverse Map" << endl;
map<string, string> :: iterator iter;
for(iter = mapNameList.begin(); iter != mapNameList.end(); iter++)
{
cout << iter -> first << " 's value is " << iter -> second << endl;
}
cout << endl;
// Erase Key
cout << "Erase Key 104 & 107" << endl;
mapNameList.erase("104");
mapNameList.erase(mapNameList.find("105"));
cout << endl;
// Traverse Map
cout << "Traverse Mag Again!" << endl;
for(iter = mapNameList.begin(); iter != mapNameList.end(); iter++)
{
cout << iter -> first << "'s value is " << iter -> second << endl;
}
cout << endl;
// Clear Map
cout << "Count of pairs: " << mapNameList.size() << endl;
mapNameList.clear();
cout << "Map Cleared!" << endl;
cout << "Count of pairs: " << mapNameList.size() << endl << endl;
cout << "Program Closed" << endl;
return 0;
}
3.makefile文件
a: a.o
g++ -o a a.o
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf *.o a
4.运行结果
END