首页 > 其他分享 >cpp get map last element

cpp get map last element

时间:2023-03-19 18:23:40浏览次数:31  
标签:std map last element mp cpp itr size

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;
        }
    } 

 

标签:std,map,last,element,mp,cpp,itr,size
From: https://www.cnblogs.com/Fred1987/p/17233850.html

相关文章