looking for a nicer solution using functionals

P

persres

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) );
}
 
F

Fulvio Esposito

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
 
R

red floyd

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 );
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top