C++的map怎么用?
时间: 2023-11-20 14:00:02 浏览: 25
好的,关于C语言中的map的使用,map是STL中的一个关联式容器,可以实现键值对的存储和查找,使用起来非常方便。可以看一下下面的示例代码:
```
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<string, int> myMap;
myMap["Tom"] = 18;
myMap["Jerry"] = 19;
myMap["Alice"] = 17;
// 查找元素
cout << "Tom's age is " << myMap["Tom"] << endl;
// 遍历map
map<string, int>::iterator it;
for (it = myMap.begin(); it != myMap.end(); it++)
{
cout << it->first << "'s age is " << it->second << endl;
}
return 0;
}
```
在这个示例代码中,我们声明了一个`map`对象`myMap`,然后插入了三组键值对。使用`[]`操作符可以访问map中的元素。遍历map可以使用迭代器,在遍历时使用`first`和`second`成员可以访问键和值。
相关问题
c++中有hash_map吗?
在C++中,标准库提供了一个名为`unordered_map`的哈希表容器,用于实现键值对的存储和快速查找。`unordered_map`是C++中的哈希表实现,提供了常数时间的平均插入、删除和查找操作。它类似于`hash_map`,但是`hash_map`不是C++标准库的一部分,而是一些特定实现(例如,Visual C++)提供的扩展。因此,在C++中,推荐使用`unordered_map`来代替`hash_map`。
C++ map 使用教程
C++中的map是一种关联式容器,它提供了一种将键映射到值的方法。map中的每个元素都是一个键值对,其中键是唯一的,值可以重复。使用map可以快速查找和访问元素,其底层实现是红黑树。下面是C++ map的使用教程:
1. 定义map对象:`map<key_type, value_type> myMap;`
2. 插入元素:`myMap.insert(pair<key_type, value_type>(key, value));`
3. 访问元素:`myMap[key]`或者`myMap.at(key)`
4. 删除元素:`myMap.erase(key)`
5. 遍历map:使用迭代器,例如:
```
map<key_type, value_type>::iterator it = myMap.begin();
for(; it != myMap.end(); it++){
cout << it->first << " " << it->second << endl;
}
```
6. 判断元素是否存在:使用find函数,例如:`myMap.find(key) != myMap.end()`