Most useful or amazing STL short liners

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

    My favorite is copying containers to the output: And copying the input stream into a container.

    #include <vector>
    #include <algorithm> 
    #include <iterator>
    #include <iostream>
    
    int main()
    {
        std::vector<int>   data;
        std::copy(std::istream_iterator<int>(std::cin),
                  std::istream_iterator<int>(),
                  std::back_inserter(data)
                 );
    
        std::copy(data.begin(),data.end(),
                  std::ostream_iterator<int>(std::cout,"\n")
                 );
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题