遍历map
时间: 2023-06-28 14:04:41 浏览: 46
遍历 map 可以使用 C++ 的迭代器,如下所示:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m = {{"apple", 5}, {"banana", 3}, {"orange", 2}};
// 使用迭代器遍历map
for (std::map<std::string, int>::iterator it = m.begin(); it != m.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
return 0;
}
```
输出结果为:
```
apple : 5
banana : 3
orange : 2
```
其中,`m.begin()` 返回指向 map 开始的迭代器,`m.end()` 返回指向 map 结尾的迭代器,`it->first` 表示迭代器指向的元素的 key,`it->second` 表示迭代器指向的元素的 value。
相关问题
c++ 遍历 map
在C++中,遍历`map`可以使用迭代器来实现。`map`是一个关联容器,它存储了一组键值对,并按照键的顺序进行排序。以下是遍历`map`的几种常见方法:
1. 使用迭代器:
```cpp
std::map<KeyType, ValueType> myMap;
// 添加键值对到myMap中
// 使用迭代器遍历map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
// 访问键和值
KeyType key = it->first;
ValueType value = it->second;
// 对键值对进行操作
}
```
2. 使用范围-based for 循环(C++11及以上版本):
```cpp
std::map<KeyType, ValueType> myMap;
// 添加键值对到myMap中
// 使用范围-based for 循环遍历map
for (const auto& pair : myMap) {
// 访问键和值
KeyType key = pair.first;
ValueType value = pair.second;
// 对键值对进行操作
}
```
3. 使用`std::for_each`算法(需要包含<algorithm>头文件):
```cpp
std::map<KeyType, ValueType> myMap;
// 添加键值对到myMap中
// 使用std::for_each算法遍历map
std::for_each(myMap.begin(), myMap.end(), [](const std::pair<KeyType, ValueType>& pair) {
// 访问键和值
KeyType key = pair.first;
ValueType value = pair.second;
// 对键值对进行操作
});
```
以上是几种常见的遍历`map`的方法,你可以根据自己的需求选择适合的方式进行遍历。
java 遍历map
在Java中遍历Map有以下几种方式:
1. 使用for-each循环遍历Map中的键值对
```java
Map<String, Integer> map = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
```
2. 使用Iterator遍历Map中的键值对
```java
Map<String, Integer> map = new HashMap<>();
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(entry.getKey() + " = " + entry.getValue());
}
```
3. 遍历Map中的键
```java
Map<String, Integer> map = new HashMap<>();
for (String key : map.keySet()) {
System.out.println(key);
}
```
4. 遍历Map中的值
```java
Map<String, Integer> map = new HashMap<>();
for (Integer value : map.values()) {
System.out.println(value);
}
```
以上就是Java中遍历Map的几种方式。需要注意的是,在遍历Map时,如果需要删除元素,建议使用Iterator遍历,并且在删除元素后调用Iterator的remove方法。