Most useful or amazing STL short liners

后端 未结 8 1058
余生分开走
余生分开走 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<int> v(20);
    
    std::for_each( v.begin(), v.end(), [] (int item)
    {
        std::cout << item;
    } );
    

    instead of

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

    makes for better looking loops.

    0 讨论(0)
  • 2021-01-29 23:02

    I like this one for looping over each line in a file. From a Andrew Koenig column in Dr. Dobbs.

    for (string s; getline(stream,s); ) {
      // Process line
    }
    
    0 讨论(0)
  • 2021-01-29 23:05

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

    vector<int> 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.

    0 讨论(0)
  • 2021-01-29 23:06
    copy(istreambuf_iterator<char>(cin), istreambuf_iterator<char>(),
         ostream_iterator<char>(cout));
    

    Another oft used idiom is initializing a container from an array:

    #include <map>
    using namespace std;
    
    int main() {
        typedef std::map<char,int> LUT;
        typedef LUT::value_type LUT_item_t;
    
        const LUT_item_t items[] = { LUT_item_t('b',1), 
                                     LUT_item_t('a',5) 
                                   };
    
        LUT my_map(items, items + sizeof items/sizeof items[0]);
        return 0;
    }
    

    But if you want pure magic, look into Boost Lambda Library ;) A sample:

    vector<int*> vp(10); 
    sort(vp.begin(), vp.end(), *_1 > *_2);
    
    0 讨论(0)
  • 2021-01-29 23:20

    For your second example use the value type:

    #

    Copy a map to a vector:
    
    typedef map<T1, T2> MyMap;
    MyMap myMap;
    vector< MyMap::value_type > myVec(myMap.begin(), myMap.end());
    
    0 讨论(0)
  • 2021-01-29 23:24
    // std::back_inserter usage ( std::inserter for map )
    std::copy( source.begin(), source.end(), std::back_inserter( container ) );  
    

    -

    // mem_fun and bind usage (but boost better)
    std::some_algorithm(..., std::mem_fun( func ) );  
    

    not so useful, but powerful:

    check is container sorted

    std::adjacent_find( container.begin(), container.end(), greater<Container::value_type>() ) == container.end()
    

    also examples mentioned by you and dirkgently.

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