// ========================================================================== // $Id: stl_array.cpp,v 1.3 2011/09/10 01:08:19 jlang Exp $ // CSI2372 example Code for lecture 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_array.cpp,v $ // Revision 1.3 2011/09/10 01:08:19 jlang // Updates F10 // // Revision 1.2 2007/09/18 00:24:50 jlang // Added comments // // Revision 1.1 2006/11/08 01:41:34 jlang // added stl code for lecture 11 // // // ========================================================================== #include #include using std::cout; using std::endl; using std::sort; using std::nth_element; using std::random_shuffle; using std::make_heap; using std::sort_heap; using std::for_each; using std::unary_function; using std::ostream; template class ValueAssign : public unary_function { T d_count; public: ValueAssign( T _count ) : d_count ( _count) {} void operator() ( T& _x ) { _x = d_count++; } }; template void Print( const T& x ) { cout << x << ' '; } int main() { // Store 25 numbers 0..24 in numbers and print int numbers[25]; for_each( &numbers[0], &numbers[25], ValueAssign(0) ); for_each( &numbers[0], &numbers[25], Print ); cout << endl; // Randomize the sequence cout << "Randomize: " << endl; random_shuffle( &numbers[0], &numbers[25] ); for_each( &numbers[0], &numbers[25], Print ); cout << endl; // select 5th element int *ptr = &numbers[4]; nth_element( &numbers[0], ptr, &numbers[25] ); cout << "5th element: " << *ptr << endl; for_each( &numbers[0], &numbers[25], Print ); cout << endl; // turn it into a heap cout << "Heapify: " << endl; make_heap( &numbers[0], &numbers[25] ); for_each( &numbers[0], &numbers[25], Print ); cout << endl; // heap sort cout << "Heap Sort: " << endl; sort_heap( &numbers[0], &numbers[25] ); for_each( &numbers[0], &numbers[25], Print ); cout << endl; return 0; }