最有用或惊人的STL短衬裤 [英] Most useful or amazing STL short liners

查看:102
本文介绍了最有用或惊人的STL短衬裤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找适合几行的C ++ / STL代码的实用和教育样本。我的实际收藏是:

I'm looking for practical and educational samples of C++ / STL code fitting in few lines. My actual favorites are:


  1. 清空向量,释放其保留的内存:

  1. Empty a vector freeing its reserved memory:

vector <...>().swap (v)


b $ b

(与暂时交换)

(swap with a temporary)

将地图复制到向量:

map<T1, T2> myMap;
vector< pair<T1, T2> > myVec(myMap.begin(), myMap.end());
// or
myVec.assign(myMap.begin(), myMap.end());


  • 自定义非提升分割:

  • Custom, non-boost split:

    vector<string> &mysplit(const string &s, char delim, vector<string> &elems) {
        stringstream ss(s);
        string item;
        while(getline(ss, item, delim)) { elems.push_back(item); }
        return elems;
    }
    



  • 推荐答案

    // 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

    check is container sorted

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

    也是你和dirkgently提到的示例。

    also examples mentioned by you and dirkgently.

    这篇关于最有用或惊人的STL短衬裤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆