| | | | STL Code Snippets
// Vector: vector vec; vec.push_back( name ); // push_back() means append vec.clear();
// Iterating thru a container: vector files; vector::iterator itr; for ( itr = files.begin(); itr != files.end(); ++itr ) cout << *itr << endl;
// Iterating by subscript using an index (N/A to associative containers): vector vec; for ( int i = 0; i < vec.size(); ++i )
// Building and iterating thru a map and using pairs: map mp; mp.insert( pair( "a", 1 ) ); mp.insert( pair( "b", 2 ) ); mp.insert( pair( "c", 3 ) ); map::iterator itr; for ( itr = mp.begin(); itr != mp.end(); ++itr ) cout << itr->first << " " << itr->second << endl;
// To test if a key exists in a map/set: if ( mMap.find(key) != mMap.end() )
// Adding then removing from a container. list l; for ( int i = 0; i < 10; ++i ) l.push_back( i ); // append while ( ! l.empty() ) { // Prints/pops oldest (head) element first, cout << l.front() << endl; l.pop_front(); }
// If no match. if ( map.find("key") == map.end() ) cout << "not found" << endl;
// Print a container. list con; copy( con.begin(), con.end(), ostream_iterator(cout," ") );
// Copy a container: copy( con1.begin(), con1.end(), con2 ); // WRONG/PITFALL if con2 smaller than con1
con2.clear(); copy( con1.begin(), con1.end(), back_inserter(con2) ); // OK if con2 smaller than con1
// Sorting using a binary predicate: // An alternative (using the container container pointers instead // of values) that doesn't need a binary predicate is to define // your own operator<() which sort() uses by default. bool BinPred( const Class& o1, const Class& o2 ) { return o1.val < o2.val; } vector vec; sort( vec.begin(), vec.end(), BinPred );
// A function that returns a pair. // The pair is returned by value (like a struct would be, so it isn't dangling). std::pair
AddMul( float x, float y ) { std::pair res; res.first = x + y; res.second = x * y; return res; }
// Print a binary number in base 2 using bitset. #include bitset<8> val = 0xff; cout << val;
// Turn string to all upper-case. string s; transform( s.begin(), s.end(), s.end(), toupper );
// Distance between two iterators. distance( itr1, itr2 )
// Getting the iterator of an item that was inserted into a map: // (a multimap/multiset differs, adapted from gfx_share.hh) std::pair insertion; insertion = mMap.insert( std::make_pair( *obj, std::make_pair(copy,1) ) ); itr = insertion.first; // insertion is assumed to succeed (bool not checked)
// Replacing/substituting chars of a string. // string::replace() is really an overwrite, not a substitution. char Unix2DosDirChar( char c ) { return c == '/' ? '\': c; } string Unix2DosDir( const string& dirname ) { string s = dirname; std::transform( s.begin(), s.end(), s.begin(), Unix2DosDirChar ); return s; }
| | | | |
|
No comments:
Post a Comment