max_element with binary predicate

M

Mark P

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<int> v;
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;
}
 
M

Markus Moll

Hi

Mark said:
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 [...]
int idx = max_element( v.begin(), v.end(), CloserTo<int>( target));

Your problem is that max_element returns an iterator (to the maximum
element) rather than the element itself.

hth
Markus
 
M

Mark P

Markus said:
Hi

Mark said:
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 [...]
int idx = max_element( v.begin(), v.end(), CloserTo<int>( target));

Your problem is that max_element returns an iterator (to the maximum
element) rather than the element itself.

hth
Markus

Oh, jeez, how embarrassing. Thank you!

Mark
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top