迭代器

#include <map>
#include <iostream>
 
int main() {
    std::map<int, std::string> myMap = {{1, "一"}, {2, "二"}, {3, "三"}};
    
    // 方法1:使用迭代器
    for(std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }
    
    // 方法1的简化版(使用auto - C++11及以上)
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }
    
    return 0;
}

for 循环 C++11

#include <map>
#include <iostream>
 
int main() {
    std::map<int, std::string> myMap = {{1, "一"}, {2, "二"}, {3, "三"}};
    
    // 方法2:使用范围for循环(更简洁)
    for (const auto& pair : myMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    
    // C++17可以使用结构化绑定
    for (const auto& [key, value] : myMap) {
        std::cout << key << ": " << value << std::endl;
    }
    
    return 0;
}

STL 算法 C++17

#include <map>
#include <iostream>
#include <algorithm>
 
int main() {
    std::map<int, std::string> myMap = {{1, "一"}, {2, "二"}, {3, "三"}};
    
    // 方法3:使用for_each算法
    std::for_each(myMap.begin(), myMap.end(), [](const auto& pair) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    });
    
    return 0;
}