unordered_map遍历 可以使用数组下标方式吗
时间: 2024-02-06 17:04:15 浏览: 28
是的,对于C++中的`unordered_map`,你可以使用数组下标方式进行遍历。`unordered_map`是一个哈希表,它存储的是键值对。你可以使用迭代器或者范围循环来遍历它。
使用数组下标方式遍历`unordered_map`,你可以通过循环来遍历所有的键,然后通过键来访问对应的值。下面是一个示例代码:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
for (int i = 1; i <= 3; i++) {
std::cout << "Key: " << i << ", Value: " << myMap[i] << std::endl;
}
return 0;
}
```
输出结果为:
```
Key: 1, Value: one
Key: 2, Value: two
Key: 3, Value: three
```
请注意,当使用数组下标访问时,如果键不存在于`unordered_map`中,将会插入一个新的键值对到`unordered_map`中。因此,在使用数组下标方式遍历之前,请确保键存在于`unordered_map`中,或者使用`count()`函数进行判断。
希望这个回答能够帮助到你!如果你有更多问题,请继续提问。