c++ - binary_search with std::pair using a custom operator -


i trying binary_search including vector of integer pairs , integer follows:

#include <vector> #include <algorithm> using namespace std;  typedef vector<pair<size_t,size_t> > int_pairs;  bool operator<(const size_t& l, const pair<size_t,size_t>& r)     {return r.first < l;} // useful binary search  int main(){     int_pairs pairs_vec;     pairs_vec.push_back(pair <size_t,size_t>(1,2));     pairs_vec.push_back(pair <size_t,size_t>(2,2));     size_t i(2);     binary_search(pairs_vec.begin(),pairs_vec.end(),i); } 

the compiler tells me operator< not defined:

erreur: no match ‘operator<’ (operand types ‘const long unsigned int’ , ‘std::pair<long unsigned int, long unsigned int>’) 

am doing right way? tried change definition of operator in many different ways, nothing seems work.

the reason doesn't work operator< isn't looked point call binary_search, rather later inside body - , that's inside namespace std.

since std::pair defines relational operators in namespace std, these hide overload in global scope , it's never found name lookup.

the solution not use operator< @ all. create own comparator class doesn't clash anything, overload operator(), , use other overload of binary_search lets specify custom comparator. this:

#include <vector> #include <algorithm> using namespace std;  typedef pair<size_t, size_t> my_pair; typedef vector<pair<size_t,size_t> > int_pairs;  struct comp {     // important: need 2 overloads, because comparison     // needs done both ways check equality      bool operator()(my_pair p, size_t s) const     { return p.first < s; }     bool operator()(size_t s, my_pair p) const     { return s < p.first; } };  int main(){     int_pairs pairs_vec;     pairs_vec.push_back(pair <size_t,size_t>(1,2));     pairs_vec.push_back(pair <size_t,size_t>(2,2));     size_t i(2);     binary_search(pairs_vec.begin(),pairs_vec.end(),i, comp()); } 

side notes:

your attempt @ operator< wrong, because switched order of operands inside function. contract comparators strict weak ordering says must return true if first operand comes before second (this goes comparison functions throughout standard library).

bool operator<(const size_t& l, const pair<size_t,size_t>& r) {     return r.first < l; // wrong! } 

and said above in comment, if operands comparison of different types, you'll need 2 overloads. check equality <, need 2 test:

(!(a < b) && (!b < a)) 

Comments

Popular posts from this blog

ruby on rails - Is it the correct way to implement belongs_to relation with factory girl? -

geolocation - Windows Phone 8 - Keeping background location tracking active beyond four hours -

Uncaught TypeError: Cannot read property 'parentNode' of null javascript -