Most useful or amazing STL short liners

后端 未结 8 1068
余生分开走
余生分开走 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:26

    What I like most is to use bind1st/bind2nd/mem_fun in sort of delegates.

    // will call a->func(v[i])
    for_each(v.begin(), v.end(), bind1st(mem_fun(&A::func), &a));
    
    // will call w[i]->func(72)
    for_each(w.begin(), w.end(), bind2nd(mem_fun(&A::func), 72));
    

    Using boost's bind and function are much better, but it is impressive which can be done with just STL.

提交回复
热议问题