温馨提示×

C++遍历map的方式有哪些

c++
小亿
100
2023-12-26 16:47:52
栏目: 编程语言

在C++中,有以下几种方式可以遍历map:

  1. 使用迭代器:使用begin()和end()函数获取map的起始和终止迭代器,然后使用循环遍历迭代器来访问map中的每个元素。
std::map<int, std::string> myMap;
// 添加元素到myMap
for(auto it = myMap.begin(); it != myMap.end(); ++it) {
    std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
  1. 使用范围for循环:使用范围for循环可以方便地遍历map中的每个元素。
std::map<int, std::string> myMap;
// 添加元素到myMap
for(auto& pair : myMap) {
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
  1. 使用auto关键字:使用auto关键字可以更简洁地遍历map中的每个元素。
std::map<int, std::string> myMap;
// 添加元素到myMap
for(auto pair : myMap) {
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}

这些都是常用的遍历map的方式,根据个人习惯和需求选择适合的方式即可。

0