举个例子使用map比unordered map好
时间: 2023-04-01 11:01:07 浏览: 52
使用map比unordered map好的一个例子是需要按照键的顺序进行遍历时。因为map内部是按照键的大小进行排序的,所以遍历时可以保证按照键的顺序进行。而unordered map则是无序的,遍历时无法保证顺序。当然,在其他情况下,unordered map也可能比map更适合使用,具体要根据具体情况来决定。
相关问题
举个例子使用unordered 、map
可以使用unordered_map来实现哈希表,它可以快速地进行查找、插入和删除操作。例如,我们可以使用unordered_map来统计一个字符串中每个字符出现的次数:
```
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main()
{
string s = "hello world";
unordered_map<char, int> mp;
for (char c : s) {
mp[c]++;
}
for (auto p : mp) {
cout << p.first << ": " << p.second << endl;
}
return ;
}
```
这段代码会输出每个字符出现的次数,例如:
```
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1
```
告诉我unordered_map 使用的例子
当然可以!unordered_map 是 C++ STL 中的一个容器,用于存储键值对,可以快速地根据键找到对应的值。下面是一个简单的例子:
```c++
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<std::string, int> umap;
// 插入键值对
umap.insert({"apple", 1});
umap.insert({"banana", 2});
umap.insert({"orange", 3});
// 根据键查找值
std::cout << "The value of apple is: " << umap["apple"] << std::endl;
std::cout << "The value of banana is: " << umap["banana"] << std::endl;
std::cout << "The value of orange is: " << umap["orange"] << std::endl;
return 0;
}
```
输出结果应该是:
```
The value of apple is: 1
The value of banana is: 2
The value of orange is: 3
```
希望这个例子对您有帮助!