C++怎么遍历map集合
在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。
版权声明
本文仅代表作者观点,不代表米安网络立场。
				上一篇:云主机和vps有什么不同				下一篇:vb计时器倒计时怎么实现			
		 博豪信息
博豪信息


 
		
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。