// algorithms // demonstrate sort, #include #include #include #include #include using namespace std; void show( vector & v ) { vector::iterator I = v.begin( ); while( I != v.end( ) ) { cout << *I << ", "; I++; } cout << endl; } void sortAscending( vector & v ) { vector::iterator B = v.begin( ); vector::iterator E = v.end( ); cout << "Sorting in ascending order..." << endl; sort( B, E ); show( v ); } bool gtrThan( int X, int Y ) { return X > Y; } void sortDescending( vector & v ) { vector::iterator B = v.begin( ); vector::iterator E = v.end( ); cout << "Sorting in descending order..." << endl; sort( B, E, gtrThan ); show( v ); } void findExample( vector & v ) { vector::iterator where; where = find( v.begin( ), v.end( ), 58 ); if( where == v.end( ) ) cout << "Value not found" << endl; else cout << "Value found: " << *where << endl; } bool pred( int X ) { return X > 50; } void countExample( vector & v ) // count the number of elements that cause the // pred() function to return true. { int n = count_if( v.begin( ), v.end( ), pred ); cout << "count_if: " << n << endl; } void randomShuffle( vector & v ) // shuffle elements randomly { cout << "Randomly shuffling elements...\n"; random_shuffle( v.begin( ), v.end( ) ); show( v ); } void printSquare( int x ) // displays the square of each value { cout << x * x << ", "; } void forEachExample( vector & v ) { cout << "Calling printSquare for each element:\n"; for_each( v.begin( ), v.end( ), printSquare ); cout << endl; } int main() { vector v; for( int i = 0; i < 10; i++ ) v.push_back( rand( ) % 100 ); cout << "Original order...\n"; show( v ); //sortAscending( v ); //sortDescending( v ); //randomShuffle( v ); //findExample( v ); //countExample( v ); forEachExample( v ); return 0; }