Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   looking for a nicer solution using functionals (http://www.velocityreviews.com/forums/t754242-looking-for-a-nicer-solution-using-functionals.html)

persres@googlemail.com 09-19-2011 05:50 PM

looking for a nicer solution using functionals
 
Hi,
I need to do the following. I really feel I should be able to
do it using some existing standard functionals either in boost or stl.

Does anyone have suggestions.

template <class T>
struct maxif : binary_function<int, int, void>
{
void operator() (const int&s, int& d) const
{
if (d < s)
d = s;
}
};
void UpdateIfLessThanVal(vector<int> v, const int val)
{
for_each(v.begin(), v.end(), bind1st(maxif <int> (), val) );
}



Fulvio Esposito 09-19-2011 06:52 PM

Re: looking for a nicer solution using functionals
 
If I understand you would set a minimum value to all vectors elements? so if you have

std::vector< int > v = { 1, 2, 3, 4, 5, 6 };
UpdateIfLessThanVal( v, 4 );

// now v is { 4, 4, 4, 4, 5, 6 }

am I right?

using standard algorithms you could write:

void UpdateIfLessThanVal(vector<int>& v, const int val)
{
std::replace_if( v.begin(), v.end(),
std::bind2nd( std::less< int >(), val ), val );
}

or in C++0x with lambdas (a bit of genericity as a plus)

template< typename ForwardIterator, typename T >
void UpdateIfLessThanVal( ForwardIterator first,
ForwardIterator last,
const T& val )
{
std::replace_if( first, last, [ &val ]( const T& elem )
{
return elem < val;
}, val );
}

Hope this help,
Cheers,
Fulvio

red floyd 09-19-2011 09:16 PM

Re: looking for a nicer solution using functionals
 
On 9/19/2011 11:52 AM, Fulvio Esposito wrote:
> If I understand you would set a minimum value to all vectors elements? so if you have
>
> std::vector< int> v = { 1, 2, 3, 4, 5, 6 };
> UpdateIfLessThanVal( v, 4 );
>
> // now v is { 4, 4, 4, 4, 5, 6 }
>
> am I right?
>
> using standard algorithms you could write:
>
> void UpdateIfLessThanVal(vector<int>& v, const int val)
> {
> std::replace_if( v.begin(), v.end(),
> std::bind2nd( std::less< int>(), val ), val );
> }
>


I was going to suggest std::transform, but yours is better.

And to make things generic:

template<typename T>
void UpdateIfLessThanVal(std::vector<T>& v, const T& val)
{
std::replace_if(v.begin(), v.end(),
std::bind2nd(std::less<T>(), val),
val );
}

persres@googlemail.com 09-20-2011 02:49 PM

Re: looking for a nicer solution using functionals
 
replace_if is perfect. Thank you.


All times are GMT. The time now is 08:25 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


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