1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
//----------------------------------------------------------------------------
// This method uses the STL normally.
// Again, it does NOT preserve the order of elements.
//
// You'll notice, of course, that this does produce a differently-ordered
// list than the previous method.
//
template <typename T>
void update( vector <T> & nums, const T max_value )
{
typedef vector <T> nums_t;
typedef typename nums_t::iterator iterator_t;
typedef typename nums_t::const_iterator const_iterator_t;
// We want to keep the first two elements of the old list... (as per requirement)
nums_t first_two( nums.begin(), nums.begin() + 2 );
// Now we want to split the elements between:
// nums <-- those <= 1.0
// bigs <-- those > 1.0, which we will subdivide in the next step
iterator_t bound = partition(
nums.begin(), nums.end(), bind2nd( less_equal <float> (), max_value )
);
nums_t bigs( bound, nums.end() );
nums.erase( bound, nums.end() );
// Subdivide the bigs and append the results to the nums array
for (const_iterator_t num = bigs.begin(); num != bigs.end(); ++num)
{
unsigned n = ceil( *num / max_value );
nums.insert( nums.end(), n, *num / n );
}
// Fix the head of the list so that it has those two original values...
nums.insert( nums.begin(), first_two.begin(), first_two.end() );
}
//----------------------------------------------------------------------------
// Simple way to determine the number of elements in an array[]
template <typename T, size_t N>
inline size_t SizeOfArray( const T (&)[ N ] )
{
return N;
}
//----------------------------------------------------------------------------
// A little helper to display our vectors...
template <typename T>
void display( const vector <T> & nums )
{
copy( nums.begin(), nums.end(), ostream_iterator <T> ( cout, " " ) );
cout << endl;
}
//----------------------------------------------------------------------------
int main()
{
const float MAX_VALUE = 1.0f;
const float NUMS[] = { 2.4f, 3.6f, 2.0f, 4.0f, 0.5f, 1.5f, 3.0f, 1.0f, 2.0f };
typedef vector <float> nums_t;
nums_t nums( NUMS, NUMS + SizeOfArray( NUMS ) );
cout << fixed << setprecision( 2 );
display( nums );
update( nums, MAX_VALUE );
display( nums );
return 0;
}
|