unique implementation

http://www.cplusplus.com/reference/algorithm/unique/


The behavior of this function template is equivalent to:

1
2
3
4
5
6
7
8
9
10
11
template <class ForwardIterator>
  ForwardIterator unique ( ForwardIterator first, ForwardIterator last )
{
  ForwardIterator result=first;
  while (++first != last)
  {
    if (!(*result == *first))  // or: if (!pred(*result,*first)) for the pred version
      *(++result)=*first;
  }
  return ++result;
}


Am I missing something here,seems that *(++result)=*first; is trying to assign the *first to *first which are the same ?
No, *++first will be assigned to *++first (don't evaluate that twice, mind you), but only if it isn't equal to *first.
Last edited on
Before loop :

first = 1st
result = 1st

In 1st loop :

first = 2nd //while (++first != last)
1st not equal to 2nd //if (!(*result == *first))
result = 2nd //*(++result)
2nd = 2nd // *(++result)=*first;




??????
Last edited on
Yes.
Ok then the assignment should have defined the case when 2 sides of the = are the same.
Then every assignment would require an additional comparison for equality, while as a result, you only save assignments if there's a large number of unique values at the beginning of the range.
Topic archived. No new replies allowed.