Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::unique

Use case

Remove consecutive duplicates.

Explanation

Only removes adjacent duplicates (sort first for true uniqueness). Returns iterator to new end. Like remove, requires erase to actually shrink container.

Time complexity: O(n). Single pass comparing adjacent elements. See possible implementation.

Code

#include <algorithm>
#include <cstdint>
#include <print>
#include <vector>

int main() {
  std::vector<uint64_t> addresses = {0x1000, 0x1000, 0x1000,
                                     0x1040, 0x1080, 0x1080};

  auto newEnd = std::unique(addresses.begin(), addresses.end());

  addresses.erase(newEnd, addresses.end());

  for (const auto &addr : addresses) {
    std::println("{:#x}", addr);
  }

  return 0;
}

View on GitHub.

Output

$ ./src/algorithms/build/std-unique
0x1000
0x1040
0x1080