How can I detect the last iteration in a loop over std::map?

前端 未结 15 1366
深忆病人
深忆病人 2021-01-01 10:24

I\'m trying to figure out the best way to determine whether I\'m in the last iteration of a loop over a map in order to do something like the following:

for          


        
15条回答
  •  灰色年华
    2021-01-01 11:13

    Full program:

    #include 
    #include 
    
    void process(int ii)
    {
       std::cout << " " << ii;
    }
    
    int main(void)
    {
       std::list ll;
    
       ll.push_back(1);
       ll.push_back(2);
       ll.push_back(3);
       ll.push_back(4);
       ll.push_back(5);
       ll.push_back(6);
    
       std::list::iterator iter = ll.begin();
       if (iter != ll.end())
       {
          std::list::iterator lastIter = iter;
          ++ iter;
          while (iter != ll.end())
          {
             process(*lastIter);
             lastIter = iter;
             ++ iter;
          }
          // todo: think if you need to process *lastIter
          std::cout << " | last:";
          process(*lastIter);
       }
    
       std::cout << std::endl;
    
       return 0;
    }
    

    This program yields:

     1 2 3 4 5 | last: 6
    

提交回复
热议问题