C++ 字典存储集合
时间: 2023-08-16 07:10:09 浏览: 44
C++ 中可以使用 STL 的 map 或 unordered_map 来实现字典存储集合。map 是一个基于红黑树实现的关联式容器,可以自动按照 key 排序,而 unordered_map 是一个基于哈希表实现的关联式容器,查找速度会比 map 快,但是不保证元素的顺序。以下是两种容器的使用示例:
使用 map:
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> dict;
dict["apple"] = 1;
dict["banana"] = 2;
dict["orange"] = 3;
cout << "The value of apple is " << dict["apple"] << endl;
cout << "The value of banana is " << dict["banana"] << endl;
cout << "The value of orange is " << dict["orange"] << endl;
return 0;
}
```
使用 unordered_map:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> dict;
dict["apple"] = 1;
dict["banana"] = 2;
dict["orange"] = 3;
cout << "The value of apple is " << dict["apple"] << endl;
cout << "The value of banana is " << dict["banana"] << endl;
cout << "The value of orange is " << dict["orange"] << endl;
return 0;
}
```
以上代码输出结果相同,但使用 unordered_map 的查找速度更快。