C++怎么遍历map集合

c++
357
2023/12/24 17:47:57
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用迭代器来遍历std::map集合。以下是遍历std::map的示例代码:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;
    
    // 向map中插入元素
    myMap.insert(std::make_pair(1, "apple"));
    myMap.insert(std::make_pair(2, "banana"));
    myMap.insert(std::make_pair(3, "orange"));
    
    // 使用迭代器遍历map
    std::map<int, std::string>::iterator itr;
    for(itr = myMap.begin(); itr != myMap.end(); ++itr) {
        std::cout << "Key: " << itr->first << ", Value: " << itr->second << std::endl;
    }
    
    return 0;
}

上述代码创建了一个std::map对象myMap并插入了三个键值对。然后使用迭代器itr遍历myMap,并输出每个键值对的键和值。

输出结果为:

Key: 1, Value: apple
Key: 2, Value: banana
Key: 3, Value: orange

注意,std::map是有序的,键值对按照键的自然顺序进行排序。如果需要按照插入顺序遍历集合,可以使用std::unordered_map代替std::map

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++无法启动程序怎么解决