对 map 进行遍历可以使用迭代器或者 range 循环来实现。以下是两种常用的遍历方式:

  1. 使用迭代器遍历 map:
#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;
    myMap[1] = 'apple';
    myMap[2] = 'banana';
    myMap[3] = 'orange';

    // 使用迭代器遍历 map
    std::map<int, std::string>::iterator it;
    for (it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << it->first << ' : ' << it->second << std::endl;
    }

    return 0;
}
  1. 使用 range 循环遍历 map(C++11及以上版本支持):
#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;
    myMap[1] = 'apple';
    myMap[2] = 'banana';
    myMap[3] = 'orange';

    // 使用 range 循环遍历 map
    for (const auto& pair : myMap) {
        std::cout << pair.first << ' : ' << pair.second << std::endl;
    }

    return 0;
}

以上两种方式都可以实现对 map 的遍历,根据实际需求选择合适的方法即可。


原文地址: http://www.cveoy.top/t/topic/psvE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录