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

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

    The following code would be optimized by a compiler so that to be the best solution for this task by performance as well as by OOP rules:

    if (&*it == &*someMap.rbegin()) {
        //the last iteration
    }
    

    This is the best code by OOP rules because std::map has got a special member function rbegin for the code like:

    final_iter = someMap.end();
    --final_iter;
    
    0 讨论(0)
  • 2021-01-01 10:59

    Since C++11, you can also use std::next()

       for (auto iter = someMap.begin(); iter != someMap.end(); ++iter) { 
            // do something for all iterations
            if (std::next(iter) != someMap.end()) {
                // do something for all but the last iteration
            }
        }
    

    Although the question was asked a while ago, I thought it would be worth sharing.

    0 讨论(0)
  • 2021-01-01 10:59

    Surprised no one mentioned it yet, but of course boost has something ;)

    Boost.Next (and the equivalent Boost.Prior)

    Your example would look like:

    for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
        // do something for all iterations
        if (boost::next(iter) != someMap.end()) {
            // do something for all but the last iteration
        }
    }
    
    0 讨论(0)
  • 2021-01-01 11:02

    Canonical? I can't claim that, but I'd suggest

    final_iter = someMap.end();
    --final_iter;
    if (iter != final_iter) ...
    

    Edited to correct as suggested by KTC. (Thanks! Sometimes you go too quick and mess up on the simplest things...)

    0 讨论(0)
  • 2021-01-01 11:02

    Here's my optimized take:

    iter = someMap.begin();
    
    do {
        // Note that curr = iter++ may involve up to three copy operations
        curr = iter;
    
        // Do stuff with curr
    
        if (++iter == someMap.end()) {
            // Oh, this was the last iteration
            break;
        }
    
        // Do more stuff with curr
    
    } while (true);
    
    0 讨论(0)
  • 2021-01-01 11:04

    This seems like the simplest:

    bool last_iteration = iter == (--someMap.end());
    
    0 讨论(0)
提交回复
热议问题