cpp get map last element

复制代码
void util::print_map(const std::map<int,std::string> &mp)
{
    std::cout << get_time_now() << ",std::this_thread::get_id()= " << std::this_thread::get_id() << ", started in " << std::string(__FILE__) << "," << std::string(__FUNCTION__)
                  << "," << std::to_string(__LINE__) << std::endl;
    auto itr=mp.begin();
    while(itr!=mp.end())
    {
        std::cout<<"Key="<<itr->first<<",value="<<itr->second<<std::endl;
        itr=std::next(itr,1000000);
    }

    int len=mp.size();
    int idx=0;
    for(auto itr=mp.begin();itr!=mp.end();itr++)
    {
        if(++idx==len)
        {
            std::cout<<"Last element,Key="<<itr->first<<",value="<<itr->second<<std::endl;
        }
    } 
    std::cout << get_time_now() << ",std::this_thread::get_id()= " << std::this_thread::get_id() << ", finished in " << std::string(__FILE__) << "," << std::string(__FUNCTION__)
                  << "," << std::to_string(__LINE__) << std::endl;
}
复制代码

The critical way located at retrieve the map elements count via size(),then iterate the map util to the end while increment the third temperatory variable,while the medium variable add 1 equals to the size of the map.in the for loop,the itr is the last element

复制代码
int len=mp.size();
    int idx=0;
    for(auto itr=mp.begin();itr!=mp.end();itr++)
    {
        if(++idx==len)
        {
            std::cout<<"Last element,Key="<<itr->first<<",value="<<itr->second<<std::endl;
        }
    } 
复制代码

 

posted @   FredGrit  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2022-03-19 C++original fatorial and optimized factorial method
2022-03-19 C++ optimized fibonacci algorithm
2022-03-19 C++ quick sort ascendingly and descendingly
2022-03-19 C++ write file and read file via fstream
2022-03-19 C++ vector iterator std::ref(vec)
2022-03-19 C++ selection sort.quick sort
2020-03-19 TripleDESCryptoServiceProvider CryptoStream
点击右上角即可分享
微信分享提示