#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, string> m1;
m1.insert(pair<int, string>(1, "one"));
m1.insert(pair<int, string>(2, "two"));
m1.insert(pair<int, string>(3, "three"));
map<int, string>::iterator iter1;
for (iter1 = m1.begin(); iter1 != m1.end(); iter1++)
{
cout << iter1->first << " " << iter1->second << endl;
}
// 用数组方式添加数据
map<int, string> m2;
m2[1] = "one";
m2[2] = "two";
m2[3] = "three";
// 用数组方式遍历数据
int m2Size = m2.size();
for (int i = 1; i <= m2Size; i++)
{
cout << i << "->" << m2[i] << endl;
}
// 查找 find()
iter1 = m1.find(1);
if (iter1 != m1.end())
{
cout << iter1->second << endl;
}
else
{
cout << "Do not found!" << endl;
}
// 删除元素
m1.erase(iter1);
int m1Size = m1.size();
for (iter1 = m1.begin(); iter1 != m1.end(); iter1++)
{
cout << iter1->first << " " << iter1->second << endl;
}
return 0;
}
C++STL之Map基础使用
529 views