This is the code from the C++ standard library remove
code. Why is inequality tested as if (!(*first == val))
instead of if (*first != val)
?
template <class ForwardIterator, class T> ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val) { ForwardIterator result = first; while (first!=last) { if (!(*first == val)) { *result = *first; ++result; } ++first; } return result; }
The inequality operator ( != ) checks whether its two operands are not equal, returning a Boolean result.
The equality operators in C++ are is equal to(==) and is not equal to(!=). They do the task as they are named. The binary equality operators compare their operands for strict equality or inequality. The equality operators, equal to (==) and not equal to (!
Because this means the only requirement on T is to implement an operator==
. You could require T to have an operator!=
but the general idea here is that you should put as little burden on the user of the template as possible and other templates do need operator==
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With