C=+中的Dictionary类
时间: 2023-11-28 20:51:12 浏览: 47
C++ 中没有内置的 Dictionary 类,但可以使用 STL 中的 map 或 unordered_map 来实现类似于字典的功能。
map 是一个关联容器,可以将键和值进行映射,类似于字典中的键值对。它会按照键的大小进行排序,因此查找操作的效率较高,但插入和删除操作的效率较低。
unordered_map 也是一个关联容器,但它不会按照键的大小进行排序,因此插入和删除操作的效率较高,但查找操作的效率略低于 map。
下面是使用 map 实现字典功能的示例代码:
```c++
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> dict; // 定义一个字符串到整数的映射
// 向字典中添加键值对
dict["apple"] = 1;
dict["banana"] = 2;
dict["orange"] = 3;
// 查找键对应的值
std::cout << dict["apple"] << std::endl; // 输出 1
// 遍历字典中的所有键值对
for (auto it = dict.begin(); it != dict.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
```
输出结果为:
```
1
apple: 1
banana: 2
orange: 3
```