Most useful or amazing STL short liners

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

    copy(istreambuf_iterator(cin), istreambuf_iterator(),
         ostream_iterator(cout));
    

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

    #include 
    using namespace std;
    
    int main() {
        typedef std::map 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 vp(10); 
    sort(vp.begin(), vp.end(), *_1 > *_2);
    

提交回复
热议问题