map c++ 简单实现
时间: 2023-05-03 08:06:30 浏览: 91
map是STL库中的一个关联容器,它能够把一些键值和其关联起来。在C++中,可以通过创建一个map对象来使用这个容器,以实现快速且方便的数据查找和存储。
在实现map的过程中,我们需要注意以下几点:
1. 头文件
使用map时需要引入C++中的map头文件,即#include<map>。
2. 命名空间
因为map属于STL库,所以在使用时需要在命名空间std中定义。
3. 关键字
map的关键字是唯一的,需要用unique的关键字来约束。
下面是一个简单实现map的例子,包括了定义、插入、遍历等操作:
#include <iostream>
#include <map>
using namespace std;
int main()
{
//定义一个map
map<int, string> myMap;
//在map中插入元素
myMap.insert(pair<int, string>(1, "apple"));
myMap.insert(pair<int, string>(2, "banana"));
myMap.insert(pair<int, string>(3, "orange"));
myMap.insert(pair<int, string>(4, "grape"));
//遍历map中的所有元素
for(map<int, string>::iterator it = myMap.begin(); it != myMap.end(); it++)
{
cout << it->first << ": " << it->second << endl;
}
//通过key访问value
cout << "The value of key 3 is: " << myMap[3] << endl;
//通过key修改value
myMap[3] = "lemon";
cout << "After modified, the value of key 3 is: " << myMap[3] << endl;
//删除指定的元素
myMap.erase(2);
//再次遍历map中的所有元素
for(map<int, string>::iterator it = myMap.begin(); it != myMap.end(); it++)
{
cout << it->first << ": " << it->second << endl;
}
return 0;
}
运行结果如下所示:
1: apple
2: banana
3: orange
4: grape
The value of key 3 is: orange
After modified, the value of key 3 is: lemon
1: apple
3: lemon
4: grape
以上就是一个简单的map实现的例子。通过使用map,我们可以快速有效地存储和查询数据,实现了高效的数据管理。