Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Apr 24, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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:


changes their order to:


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 <int> vi;
   vi.push_back(1); // insert elements into vector
  //move consecutive duplicates past the end; store new end
   vector<int>::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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date