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

前端 未结 15 1195
深忆病人
深忆病人 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:15

    Modified Mark Ransom's so it actually work as intended.

    finalIter = someMap.end();
    --finalIter;
    if (iter != final_iter)
    
    0 讨论(0)
  • 2021-01-01 11:16

    A simple, yet effective, approach:

      size_t items_remaining = someMap.size();
    
      for (iter = someMap.begin(); iter != someMap.end(); iter++) {
        bool last_iteration = items_remaining-- == 1;
      }
    
    0 讨论(0)
  • 2021-01-01 11:19

    You can just pull an element out of the map prior to iteration, then perform your "last iteration" work out of the loop and then put the element back into the map. This is horribly bad for asynchronous code, but considering how bad the rest of C++ is for concurrency, I don't think it'll be an issue. :-)

    0 讨论(0)
提交回复
热议问题