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

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

    #include 
    #include 
    #include 
    
    using namespace boost::lambda;
    
    // call the function foo on each element but the last...
    if( !someMap.empty() )
    {
      std::for_each( someMap.begin(), --someMap.end(), bind( &Foo, _1 ) );
    }
    

    Using std::for_each will ensure that the loop is tight and accurate... Note the introduction of the function foo() which takes a single argument (the type should match what is contained in someMap). This approach has the added addition of being 1 line. Of course, if Foo is really small, you can use a lambda function and get rid of the call to &Foo.

提交回复
热议问题