Most useful or amazing STL short liners

后端 未结 8 1069
余生分开走
余生分开走 2021-01-29 22:55

I\'m looking for practical and educational samples of C++ / STL code fitting in few lines. My actual favorites are:

  1. Empty a vector freeing its reserved memory:<

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 23:00

    Using std::for_each in combination with a lambda function (since C++11)

    std::vector v(20);
    
    std::for_each( v.begin(), v.end(), [] (int item)
    {
        std::cout << item;
    } );
    

    instead of

    for(std::vector::const_iterator it = v.begin(); it != v.end(); ++it)
    {
        std::cout << *it;
    }
    

    makes for better looking loops.

提交回复
热议问题