Post

STL Tips : std::unique

std::unique remove consecutive duplicate elements from a range.

STL Tips : std::unique

STL

std::unique


1
#include <algorithm>

std::unique

  • std::unique used to remove consecutive duplicate elements from a range.
  • The duplicated elements are moved to the end, therefore deletion doesn’t happen.
  • For removing, call `container.erase(iter, container_end)

Example 01: Remove only CONSECUTIVE duplicates are removed.

1
2
3
4
5
6
7
8
9
10
std::vector<int> v = {1, 1, 2, 2, 2, 3, 3, 4, 2, 2, 5, 5, 6, 7};

auto new_end = std::unique(v.begin(), v.end());
v.erase(new_end, v.end());

for (int i : v) 
{
    std::cout << i << ' ';
}
// Output: 1 2 3 4 2 5 6 7 

Try here.


Example 02: Remove all duplicates with std::unique

1
2
3
4
5
6
7
8
std::vector<int> v = {1, 1, 2, 2, 2, 3, 3, 4, 2, 2, 5, 5, 6, 7};
std::sort(v.begin(), v.end());
auto new_end = std::unique(v.begin(), v.end());
v.erase(new_end, v.end());

for (int i : v) 
    std::cout << i << ' ';
// Output: 1 2 3 4 5 6 7 

Try here.

This post is licensed under CC BY 4.0 by the author.