Re: Overloading operator== for pair<>
"Tom Sz." <tom.usenet.73@gmail.com> writes:
Hello.
I was experimenting a bit and wrote something but the result is not
what I expected.
Can someone tell me why the code below doesn't display "Found".
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool operator== (const pair<int, int>& l, const pair <int, int>& r)
{
return l.first == r.first;
}
Here you are providing a custom op== for a standard library type,
std::pair. You should first of all be aware, if you are not already,
that one such op== already exists, declared as:
namespace std {
template <class T1, class T2>
bool operator==(const pair<T1, T2>&, const pair<T1, T2>&);
}
As this operator is declared in namespace std together with std::find,
it will be found and used by the latter and your own custom operator
will not be considered.
(To illustrate this, wrap your own custom operator in namespace std,
whereupon /it/ will be preferred as a non-template function. However,
this is by way of illustration only and should not be considered as a
solution to your problem.)
int main()
{
vector<pair<int, int> > vec;
vec.push_back(pair<int, int>(0, 0));
vec.push_back(pair<int, int>(0, 1));
vec.push_back(pair<int, int>(1, 1));
vec.push_back(pair<int, int>(2, 1));
pair<int, int> p(2, 2);
vector<pair<int, int> >::iterator it = find(vec.begin(), vec.end(),
p);
if (it != vec.end()) cout << "Found" << endl;
}
What you need here is probably a predicate and std::find_if. Something
like:
template<typename T1, typename T2>
class eq_first {
public:
eq_first(std::pair<T1, T2> p)
: p_(p)
{ }
bool operator()(std::pair<T1, T2> p)
{ return p.first == p_.first; }
private:
std::pair<T1, T2> p_;
};
// ...
std::vector<std::pair<int, int> >::iterator it =
std::find_if(vec.begin(), vec.end(), eq_first<int, int>(p));
Regards
Paul Bibbings