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 @ 2023-03-19 18:11  FredGrit  阅读(28)  评论(0)    收藏  举报