STL like container typedef shortcut?

后端 未结 7 1132
有刺的猬
有刺的猬 2021-01-26 22:56

A common pattern with STL containers is this:

map map;
for(map::iterator iter = map.begin(); iter != map.end(); ++iter)
{
  .         


        
7条回答
  •  孤街浪徒
    2021-01-26 23:23

    Over the past few years I've really tried to move away from using manually written loops in preference to using the STL algorithms. Your above code can be changed to:

    struct DoLoopBody {
      template 
      inline void operator()(ValueType v) const {
        // ...
      }
    };
    
    std::for_each (map.begin(), map.end(), DoLoopBody ());
    

    Unfortunately the class DoLoopBody cannot be a local class, which is often highlighted as a disadvantage. However, I see this as an advantage in that the body of the loop can now be unit tested in isolation.

提交回复
热议问题