Re: get the max "absolute" integer in a vector
JDT wrote:
Hi,
Can someone provide me an example that uses std::max_element()
(probablly the predicate version) to return the max "absolute" integer
in a vector? Your help is much appreciated.
Tony
ps.
// return the max integer in a vector
std::vector<int> m;
...
std::vector<int>::iterator p = std::max_element(m.begin(), m.end());
This is the traditional way. You can also attemp to make ComparisonOp
into a template if you wish.
------------------------------------------------
#include <vector>
#include <algorithm>
#include <functional>
class ComparisonOp : public std::binary_function<bool, int, int>
{
public:
result_type operator()( const first_argument_type &a,
const second_argument_type &b ) const
{
return (a < b);
}
};
int
main()
{
std::vector<int> m;
// fill m with elements
std::vector<int>::iterator p = std::max_element(m.begin(), m.end(),
ComparisonOp());
}
----------------------------------------------------------
This uses boost lambda.
----------------------------------------------------------
#include <vector>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
// this works if operator< is defined for your type (int in your case)
using namespace boost::lambda;
int
main()
{
std::vector<int> m;
// fill m with elements
std::vector<int>::iterator p =
std::max_element( m.begin(), m.end(), (_1 < _2) );
}
-------------------------------------------------------------