unordered_map遍历value
时间: 2023-09-13 19:09:01 浏览: 69
要遍历`unordered_map`中的值(value),你可以使用迭代器来访问每个键值对,然后通过获取迭代器的值部分来访问相应的值。以下是一个示例代码:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap = {
{1, "one"},
{2, "two"},
{3, "three"}
};
// 使用迭代器遍历值
for (const auto& pair : myMap) {
const std::string& value = pair.second;
std::cout << value << std::endl;
}
return 0;
}
```
上述代码中,我们创建了一个`unordered_map`,然后使用`for`循环和迭代器遍历每个键值对。在循环中,我们通过`pair.second`来获取每个键值对的值,然后将其打印输出。
输出结果:
```
one
two
three
```
这样你就可以通过迭代器遍历`unordered_map`中的所有值了。
相关问题
unordered_map 遍历
要遍历 unordered_map,你可以使用迭代器来访问其中的每个键值对。以下是一个示例代码:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap;
myMap["apple"] = 1;
myMap["banana"] = 2;
myMap["orange"] = 3;
// 使用迭代器遍历unordered_map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
```
在上面的示例中,我们创建了一个名为 `myMap` 的 unordered_map,并向其中添加了三个键值对。然后,我们使用 `begin()` 和 `end()` 函数获取 unordered_map 的起始和结束迭代器,并使用循环遍历每个键值对。通过 `it->first` 和 `it->second`,我们可以访问每个键和对应的值。
unordered_map查找value值
unordered_map是C++标准库中的一个关联容器,它基于哈希表实现。要查找unordered_map中特定value值对应的键(key),可以使用以下方法:
```cpp
#include <iostream>
#include <unordered_map>
#include <algorithm>
int main() {
std::unordered_map<int, std::string> myMap = {
{1, "apple"},
{2, "banana"},
{3, "orange"},
{4, "grape"}
};
std::string targetValue = "banana";
auto it = std::find_if(myMap.begin(), myMap.end(), [&](const auto& pair) {
return pair.second == targetValue;
});
if (it != myMap.end()) {
std::cout << "Key found: " << it->first << std::endl;
} else {
std::cout << "Key not found." << std::endl;
}
return 0;
}
```
在上面的示例中,我们创建了一个unordered_map对象myMap,并初始化了一些键值对。然后,我们定义了目标值targetValue为"banana"。使用`std::find_if`函数和lambda表达式,我们遍历unordered_map,判断每个元素的value是否等于targetValue。如果找到匹配的元素,我们输出对应的键(key);否则,输出"Key not found."。
请注意,上述代码假定unordered_map中的value都是唯一的。如果有多个value相同的键值对,上述代码只会返回第一个匹配的键。如果需要查找所有value匹配的键,可以将所有匹配的键存储在一个容器中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)