// ========================================================================== // $Id: stl_sort_C11.cpp,v 1.2 2015/11/16 16:17:15 jlang Exp $ // CSI2372 example Code for lecture 13 - C++11 // ========================================================================== // (C)opyright: // // Jochen Lang // SITE, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: jlang (Jochen Lang) // Email: jlang@site.uottawa.ca // ========================================================================== // $Log: stl_sort_C11.cpp,v $ // Revision 1.2 2015/11/16 16:17:15 jlang // More C++11 initializer lists // // Revision 1.1 2013/11/10 02:28:08 jlang // Added examples on bind and lambdas // // ========================================================================== #include #include #include #include using std::ostream; using std::cout; using std::endl; using std::vector; using std::array; using std::sort; using std::stable_sort; using std::for_each; template class Point; template ostream& operator<<( ostream& _os, const Point& _pt ); template class Point{ array d_components; public: Point(); Point( array& _components ); inline T operator()( int _dim ) const; inline T& operator()( int _dim ); friend ostream& operator<< ( ostream& _os, const Point& _pt ); }; template Point::Point() {} template Point::Point( array& _components ) : d_components(_components) {} template T Point::operator()( int _dim ) const { return d_components[_dim]; } template T& Point::operator()( int _dim ){ return d_components[_dim]; } template ostream& operator<<( ostream& _os, const Point& _pt ) { _os << "( "; for ( int i=0; i void printElements( const T& _container ) { // C++11 loop over the elements and print using auto and for range for ( auto &element : _container ) { cout << element; } cout << endl; return; } int main() { // C++11 Use of std::array with list initializer array initA{3,15}; array initB{3,13}; array initC{3,8}; array initD{1,12}; vector > pVec{initA,initB,initC,initD}; // Print unsorted printElements( pVec ); // C++11 Sort the points using a lambda sort( pVec.begin(), pVec.end(), [](const Point& _a, const Point& _b) { return _a(1)<_b(1); }); // Print sorted printElements( pVec ); // C++11 Stable sort on 1st coordinate using a lambda stable_sort( pVec.begin(), pVec.end(), [](const Point& _a, const Point& _b) { return _a(0)<_b(0); }); // C++11 Print sorted using a lambda and std::for_each (C++98) for_each( pVec.begin(), pVec.end(), [](const Point& _pt) { cout << _pt; }); cout << endl; return 0; }