Why the cryptic style?

This is the behavior of the STL unique_copy function, according to cplusplus.com:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <class InputIterator, class OutputIterator>
  OutputIterator unique_copy (InputIterator first, InputIterator last,
                              OutputIterator result)
{
  if (first==last) return result;

  *result = *first;
  while (++first != last) {
    typename iterator_traits<InputIterator>::value_type val = *first;
    if (!(*result == val))   // or: if (!pred(*result,val)) for version (2)
      *(++result)=val;
  }
  return ++result;
}


I understand the code, although I had to struggle with it at first.
What I don't understand is why, IMHO, it is written so cryptic. In particular, this part:

 
if (!(*result == val))


would be much readable if it was written:
 
if (*result != val)


The only reason I see for such a style is that, since we are dealing with generic types, this way we only need to provide the "==" operator and this is what you usually do first.

Please note, that I'm not really challenging anyone, but rather try to understand the mindset and reasoning behind the style, so that I can better learn how things work.

Thanks in advance!
Last edited on
I don't really think it is cryptic. Its a little longer, but equally readable to me. Could just be a style thing, or maybe they did have a concern about what operators exist for the items. Remember as well that the actual implementation is not this code; this code is 'equal to in behavior' but not 'the same code as' the real library.
> The only reason I see for such a style is that, since we are dealing with generic types,
> this way we only need to provide the "==" operator

The standard specifies that the predicate is equal_­to{} for the overloads in namespace std with no predicate parameter; std::equal_­to{} compares elements using operator==.

The named requirement is EqualityComparable https://en.cppreference.com/w/cpp/named_req/EqualityComparable
Ahh, thank you! Now, I see!
Topic archived. No new replies allowed.