首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何遍历/迭代STL Map?

遍历/迭代STL Map的方法有两种:一种是使用迭代器,另一种是使用基于范围的for循环。

  1. 使用迭代器:
代码语言:cpp
复制
#include<iostream>
#include <map>

int main() {
    std::map<int, std::string> my_map;
    my_map[1] = "one";
    my_map[2] = "two";
    my_map[3] = "three";

    for (std::map<int, std::string>::iterator it = my_map.begin(); it != my_map.end(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second<< std::endl;
    }

    return 0;
}
  1. 使用基于范围的for循环(C++11及以上版本):
代码语言:cpp
复制
#include<iostream>
#include <map>

int main() {
    std::map<int, std::string> my_map;
    my_map[1] = "one";
    my_map[2] = "two";
    my_map[3] = "three";

    for (const auto &pair : my_map) {
        std::cout << "Key: "<< pair.first << ", Value: "<< pair.second<< std::endl;
    }

    return 0;
}

这两种方法都可以遍历STL Map中的所有元素,并输出它们的键和值。在实际应用中,可以根据需要选择合适的方法。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券