C++迭代器遍历哈希表
时间: 2023-08-13 12:10:09 浏览: 116
对于C++中的哈希表(unordered_map),我们可以使用迭代器来遍历它。迭代器提供了一种访问容器元素的方式,可以按顺序遍历哈希表中的键值对。
下面是一个简单的示例代码,展示了如何使用迭代器遍历哈希表:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "orange";
// 使用 auto 关键字定义迭代器
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
```
在上面的示例中,我们首先创建了一个哈希表`myMap`,并向其中插入了三个键值对。然后使用`auto`关键字定义一个迭代器`it`,并通过`begin()`和`end()`函数获得迭代器的起始和结束位置。在循环中,我们通过`it->first`和`it->second`来访问键和值,并打印输出。循环会一直遍历到迭代器指向结束位置。
希望这个例子能够帮助你理解如何使用迭代器遍历C++中的哈希表!
相关问题
C++中哈希表如何遍历
在C++中,哈希表可以使用迭代器或范围循环进行遍历。
使用迭代器遍历哈希表的示例代码如下:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = { {"apple", 1}, {"banana", 2}, {"orange", 3} };
// 使用迭代器遍历哈希表
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
```
使用范围循环遍历哈希表的示例代码如下:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = { {"apple", 1}, {"banana", 2}, {"orange", 3} };
// 使用范围循环遍历哈希表
for (const auto& [key, value] : myMap) {
std::cout << key << ": " << value << std::endl;
}
return 0;
}
```
其中,使用auto关键字定义的迭代器it指向哈希表的第一个元素,每次遍历时先判断迭代器是否等于哈希表的end()迭代器,如果不等于,则输出当前元素的键值对,然后将迭代器指向下一个元素。使用范围循环则更加简洁,直接遍历哈希表的所有元素并输出。
c++ 哈希表的end()
C++中,哈希表的`end()`函数返回一个迭代器,指向哈希表中最后一个元素的下一个位置。如果哈希表为空,则`end()`函数返回的迭代器等同于`begin()`函数返回的迭代器。`end()`函数的返回值可以用于遍历哈希表中的元素,通常与`begin()`函数一起使用。以下是一个简单的例子:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
// 遍历哈希表
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
return 0;
}
```
输出结果为:
```
orange : 3
banana : 2
apple : 1
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)