This is the code from the C++ standard library remove
code. Why is inequality tested as if (!(*first == val))
instead of if (*first != val)
This is the code from the C++ standard library remove code.
Wrong. It's not the C++ standard library remove
code. It's one possible internal implementation of the C++ standard library remove
function. The C++ standard does not prescribe actual code; it prescibes function prototypes and required behaviours.
In other words: From a strict language point of view, the code you are seeing does not exist. It may be from some header file that comes with your compiler's standard-library implementation. Note that the C++ standard does not even require those header files to exist. Files are just a convenient way for compiler implementors to meet the requirements for a line like #include
(i.e. making std::remove
and other functions available).
Why is inequality tested as
if (!(*first == val))
instead ofif (*first != val)
?
Because only operator==
is required by the function.
When it comes to operator overloading for custom types, the language allows you to do all kinds of weird things. You could very well create a class which has an overloaded operator==
but no overloaded operator!=
. Or even worse: You could overload operator!=
but have it do completely unrelated things.
Consider this example:
#include
#include
struct Example
{
int i;
Example() : i(0) {}
bool operator==(Example const& other) const
{
return i == other.i;
}
bool operator!=(Example const& other) const
{
return i == 5; // weird, but nothing stops you
// from doing so
}
};
int main()
{
std::vector v(10);
// ...
auto it = std::remove(v.begin(), v.end(), Example());
// ...
}
If std::remove
used operator!=
, then the result would be quite different.