Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::equal_to useful?

Tags:

c++

c++11

The C++ standard library provides std::equal_to. This function object invokes operator== on type T by default.

What's the benefit of using std::equal_to? Could you provide an example where std::equal_to is useful?

like image 899
Lukáš Bednařík Avatar asked Sep 29 '15 17:09

Lukáš Bednařík


2 Answers

To be used in algorithms. It provides a functor with operator() on it, and thus can be used generically.

Specific (and contrived) example, as asked in comments:

// compare two sequences and produce a third one // having true for positions where both sequences // have equal elements std::transform(seq1.begin(), seq1.end(), seq2.begin(),                 std::inserter(resul), std::equal_to<>());  

Not sure who might need it, but it is an example.

like image 108
SergeyA Avatar answered Sep 24 '22 22:09

SergeyA


Having std::equal_to is very useful because it allows the equality comparison to be used as a functor, which means that it can be passed as an argument to templates and functions. This is something that isn't possible with the equality operator == since operators simply cannot be passed as parameters.

Consider, for example, how it can be used with std::inner_product, std::find_first_of and std::unordered_map.

like image 24
Nik Bougalis Avatar answered Sep 26 '22 22:09

Nik Bougalis