Alex Rivera | Logout

Most useful or amazing STL short liners

Asked 2009-04-09T16:47:19.877
23

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:

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

    (swap with a temporary)

  2. Copy a map to a vector:

    map<T1, T2> myMap;
    vector< pair<T1, T2> > myVec(myMap.begin(), myMap.end());
    // or
    myVec.assign(myMap.begin(), myMap.end());
    
  3. 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;
    }
    
Edit
Report

1 Answer

1

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());
answered 2009-04-09T17:58:57.927

Your Answer