Most useful or amazing STL short liners

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

    The following idiom is needed to actually remove the elements removed by remove() or remove_if():

    vector v;
    ...
    v.erase(remove(v.begin(), v.end(), 42), v.end());
    

    remove() and remove_if() just slide non-removed elements forward and report where the new range ends -- they don't (and can't) delete them because they can work on any arbitrary iterator range, not just a container.

提交回复
热议问题