Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is inequality tested as (!(a==b)) in a lot of C++ standard library code?

Tags:

c++

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;  } 
like image 490
Ahmed Nawar Avatar asked Sep 29 '15 16:09

Ahmed Nawar


People also ask

Which operator is used to check inequality?

The inequality operator ( != ) checks whether its two operands are not equal, returning a Boolean result.

How do you write an equality operator in C++?

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 (!


Video Answer


1 Answers

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==.

like image 103
Tom Tanner Avatar answered Sep 21 '22 11:09

Tom Tanner