What is the difference between operator() and operator< in C++? -


whenever have c++ entities want compare implement operator<. however, reading other people's code saw same can achieved implementing operator().

what difference between two? when should each of these operators used?

operator< canonical way define comparison operator:

struct { /* members */ }; struct b { /* members */ };  // comparison operator bool operator<(const a&, const b&); 

this gives conventional usage:

int main() {    a;    b b;     const bool result = (a < b); } 

what you've seen people creating functors; is, entire classes sole purpose wrap comparison. make these bit functions calling code, use operator():

struct { /* members */ }; struct b { /* members */ };  // comparison functor struct comparator {    bool operator()(const a&, const b&); }; 

this gives less conventional usage in code equivalent previous example:

int main() {    a;    b b;     comparator c;    const bool result = c(a,b); } 

however, wouldn't use this. functors passing algorithms (particularly in generic code). have added benefit of being able hold state, since have constructor arguments play with. makes them more flexible simple function pointer.

int main() {    std::vector<a> a(5);    b b;     comparator c;    std::sort(a.begin(), a.end(), c);     // or, simply:    std::sort(a.begin(), a.end(), comparator());     // more extensible than:    std::sort(a.begin(), a.end(), &somecomparisonfunction); } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -