I'm trying to use max_element with a binary predicate. Here's an
illustrative sample of the compilation problem I'm having. The compiler
reports:
closer.cpp:30: cannot convert `__gnu_cxx::__normal_iterator<int*,
std::vector<int, std::allocator<int >' to `int' in initialization
(line 30 is the penultimate statement of "main")
Suggestions to fix this?
Thanks,
Mark
// sample code
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
template <typename T>
T absValue( T x) { return x < 0 ? -x : x; }
template <typename T>
struct CloserTo : public std::binary_function< T, T, bool>
{
CloserTo( T target) : target( target) {}
bool operator()(T x, T y)
{ return absValue( x - target) < absValue( y - target); }
T target;
};
int main()
{
vector<intv;
v.push_back(0);
v.push_back(5);
v.push_back(10);
v.push_back(15);
v.push_back(20);
int target = 12;
int idx = max_element( v.begin(), v.end(), CloserTo<int>( target));
cout << v[idx] << endl;
}