Question: When I write an iterator for a custom container,
should I define both `operator==` and `operator!=`?

Initially I thought that I should define both, but then I read [here](https://en.cppreference.com/w/cpp/named_req/InputIterator), in the table of expressions that have to be defined, that only `i != j` has to be defined. Though, it says that it should be equivalent to `!(i==j)`, so I am not sure whether the latter should be defined or not.

In clang++-5.0, range-based for-loops work well as long as I define `!=`.

In case it is required to define `operator==` too, the next question is: why? Why not just require one of them and calculate the other automatically?

Answer: 
**tl;dr: Yes, you *should*, though for just range-based `for` you may not *need* to.**

---

Assuming from your link that you want to create a *InputIterator*:

> 
> Initially I thought that I should define both, but then I read here, in the table of expressions that have to be defined, that only `i != j` has to be defined. Though, it says that it should be equivalent to `!(i==j)`, so I am not sure whether the latter should be defined or not.
> 
> 
> 

Yes, it should. That requirement comes from *EqualityComparable*, which is also mentioned on that page (but not enumerated in the table, which does not define "inherited" requirements, or requirements that already fall into a category used elsewhere in the language).

An *InputIterator* may not be what you want; you can use the table on [this page](https://en.cppreference.com/w/cpp/iterator) to decide. But, at first glance, they *all* ultimately require *EqualityComparable* in the same way.

Range-based for is not specified in terms of iterator categories, but [it needs `++`, `!=` and `*`](https://en.cppreference.com/w/cpp/language/range-for); the tightest match for this set of requirements is *InputIterator*.

As for *why* `!=` is required as well as `==`, well, it would be possible for the standard library to use `!(x == y)` everywhere, but then if you *wanted* to provide some `!=` that was somehow cheaper then it would go unused, which would be annoying. This way, if all it does is `!(x == y)`, it takes seconds to define that and doesn't cost you anything.
> 
> Why not just require one of them and calculate the other automatically?
> 
> 
> 

Because you may want to customise it for speed *etc*.