// sorting.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include #include #include #include #include using namespace std; template void show(cont &c) { if(c.empty()) return; cont::iterator it; cout << "\n "; cout.setf(ios::showpoint); cout.precision(3); int count = 0; for(it=c.begin(); it!=c.end(); ++it) { cout << setw(8) << (*it) << " "; if(!((++count)%8)) cout << "\n "; } cout << "\n\n"; } bool greaterThanThreeQuarters(double d) { return (d > .75); } int _tmain(int argc, _TCHAR* argv[]) { // rand() generates a random integer between 0 and RAND_MAX. // We transform that into a random double between 0.0 and 1.0 // with a linear transformation. cout << "\n random vector " << "\n ==============="; vector vec; srand( (unsigned)time( NULL ) ); for(int i=0; i<25; ++i) { double temp = double(rand())/double(RAND_MAX); vec.push_back(temp); } show(vec); cout << "\n values greater than 0.75 " << "\n =========================="; cout << "\n "; vector results; vector::iterator it = vec.begin(); while(1) { it = find_if(it,vec.end(),greaterThanThreeQuarters); if(it != vec.end()) { results.push_back(*it); ++it; } else break; } show(results); cout << "\n sorted random vector " << "\n ======================"; cout << "\n"; sort(vec.begin(),vec.end()); show(vec); double hiBound = 0.5; vector::iterator upper = upper_bound(vec.begin(),vec.end(),hiBound); cout << "\n first value greater than " << hiBound << " = " << *upper; double loBound = 0.1; vector::iterator lower = lower_bound(vec.begin(), vec.end(), loBound); if(lower != vec.begin()) { cout << "\n last value less than " << loBound << " = " << *(--lower); cout << "\n the number of values between " << loBound << " and " << hiBound << " = " << int(upper - lower - 1); } else cout << "\n there is no value less than " << loBound; cout << "\n\n"; return 0; }