#include <iostream>
using namespace std;
#include "map";
#include "string";
//map的添加/遍历/删除
void main1()
{
map<int, string> map1;
//插入方法1
map1.insert(pair<int, string>(1, "teacher1"));
map1.insert(pair<int, string>(2, "teacher2"));
//插入方法2
map1.insert(make_pair(3, "teacher3"));
map1.insert(make_pair(4, "teacher4"));
//插入方法3
map1.insert(map<int, string>::value_type(5, "tracher5"));
//插入方法4
map1[6] = "teacher6";
//容器变量
for (map<int, string>::iterator it = map1.begin(); it != map1.end(); it++)
{
cout << it->first << "\t" << it->second << endl;
}
cout << endl;
//容器的删除
while (!map1.empty())
{
map<int, string>::iterator it = map1.begin();
cout << it->first << "\t" << it->second << endl;
map1.erase(it);
}
}
//使用pair判断插入结果是否成功 map1[4]="obj" 若4已存在,则会修改其值
void main2()
{
map<int, string> map1;
//插入方法1
map1.insert(pair<int, string>(1, "teacher1"));
//使用pair判断插入结果是否成功
pair<map<int, string>::iterator, bool> pair1 = map1.insert(pair<int, string>(1, "teacher11"));
if (pair1.second == true)
{
cout << pair1.first->first << "\t" << pair1.first->second << endl;
}
else
{
cout << "(1, \"teacher11\")插入失败\n";
}
map1.insert(pair<int, string>(2, "teacher2"));
//插入方法2
map1.insert(make_pair(3, "teacher3"));
map1.insert(make_pair(4, "teacher4"));
//插入方法3
map1.insert(map<int, string>::value_type(5, "tracher5"));
//插入方法4
map1[6] = "teacher6";
//容器变量
for (map<int, string>::iterator it = map1.begin(); it != map1.end(); it++)
{
cout << it->first << "\t" << it->second << endl;
}
}
//map的查找
void main3()
{
map<int, string> map1;
//插入方法1
map1.insert(pair<int, string>(1, "teacher1"));
map1.insert(pair<int, string>(2, "teacher2"));
//插入方法2
map1.insert(make_pair(3, "teacher3"));
map1.insert(make_pair(4, "teacher4"));
//插入方法3
map1.insert(map<int, string>::value_type(5, "tracher5"));
//插入方法4
map1[6] = "teacher6";
//map的查找 find
map<int, string>::iterator it = map1.find(5);
if (it == map1.end())
{
cout << "key:5 未找到" << endl;
}
else
{
cout << it->first << "\t" << it->second << endl;
}
map<int, string>::iterator it1 = map1.find(7);
if (it1 == map1.end())
{
cout << "key:7 未找到" << endl;
}
else
{
cout << it1->first << "\t" << it1->second << endl;
}
pair<map<int, string>::iterator, map<int, string>::iterator> pair1 = map1.equal_range(6);
if (pair1.first == map1.end())
{
cout << "key>=6 未找到" << endl;
}
else
{
cout << pair1.first->first << "\t" << pair1.first->second << endl;
}
if (pair1.second == map1.end())
{
cout << "key>6 未找到" << endl;
}
else
{
cout << pair1.second->first << "\t" << pair1.second->second << endl;
}
}
int main()
{
//main1();
//main2();
main3();
system("pause");
return 0;
}
c++ STL "map"
最新推荐文章于 2025-06-04 00:17:33 发布