![]() |
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) ); } |
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 |
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 ); } |
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.