The unique() Algorithm

STL’s unique() algorithm eliminates all but the first element from every consecutive group of equal elements in a sequence of elements. unique() takes two forward iterators, the first of which marks the sequence’s beginning and the second marks its end. The algorithm scans the sequence and removes repeated identical values. The duplicate values are moved to the sequence’s end. For example, applying unique to the following sequence of integers:

   1,0,0,9,2

changes their order to:

   1,0,9,2,0

unique() doesn’t really delete the duplicate values; it moves them to the container’s end. The third element in the original container is moved one position past the final 2. unique() returns an iterator pointing to the logical end of the container. In other words, it returns an iterator pointing to the element 2, not 0. You can delete all the duplicate elements that were moved past the logical end using the iterator returned from unique(). For example:

   int main()  {   vector  vi;   vi.push_back(1); // insert elements into vector   vi.push_back(0);   vi.push_back(0);   vi.push_back(9);   vi.push_back(2);  //move consecutive duplicates past the end; store new end   vector::iterator new_end=      unique(vi.begin(), vi.end());  // delete all elements past new_end    vi.erase(new_end, vi.end());}  }

unique() is useful when you want to make sure that only a single instance of a given value exists in a range, regardless of its distribution. For example, suppose you want to write an automated dictionary containing all the words Shakespeare’s texts. First, you scan all the words in his texts and store them in a vector. Next, you sort the vector using the sort() algorithm. Finally, apply the unique() algorithm to the sorted vector to move duplicate words past its logical end and erase the duplicates as shown above.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: