首页主机资讯C++ map iterator如何反向遍历

C++ map iterator如何反向遍历

时间2024-08-02 17:38:03发布访客分类主机资讯浏览1268
导读:要反向遍历C++ map,可以使用rbegin( 和rend( 方法。以下是一个示例代码: #include <iostream> #include <map> int main( { std::map&...

要反向遍历C++ map,可以使用rbegin()和rend()方法。以下是一个示例代码:

#include <
    iostream>
    
#include <
    map>


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

    // 使用反向迭代器反向遍历map
    for (auto it = myMap.rbegin();
     it != myMap.rend();
 ++it) {
    
        std::cout <
    <
     it->
    first <
    <
     " : " <
    <
     it->
    second <
    <
     std::endl;

    }
    

    return 0;

}
    

在这个示例中,我们使用rbegin()方法获取map的反向迭代器,rend()方法获取map的结束迭代器。然后使用for循环来遍历map,输出每个键值对。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: C++ map iterator如何反向遍历
本文地址: https://pptw.com/jishu/691902.html
C++ numeric中的数学函数有哪些 哪个C++ JSON库性能最优

游客 回复需填写必要信息