STL unique in C++

Level 4214 keystrokes

Removes consecutive duplicates with unique followed by erase, so the sorted vector shrinks to 1 2 3 4 5.

C++ code

// Sorted data, so equal values are next to each other
1vector<int> nums = {1, 1, 2, 2, 2, 3, 3, 4, 5, 5};
// unique keeps the first of each run of equal elements and returns the new logical end; the size does not change yet
2auto it = unique(nums.begin(), nums.end());
// erase removes the leftover elements from it to the end
3nums.erase(it, nums.end());
// Prints Size: 5
4cout << "Size: " << nums.size() << endl;
// Prints 1 2 3 4 5
5for (int n : nums) cout << n << " ";
6cout << endl;

Output

Size: 5
1 2 3 4 5 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 13
  • ,× 11
  • (× 7
  • )× 7
  • ;× 6
  • .× 5
  • "× 4
  • :× 2
  • =× 2
  • {× 1

More C++ examples at level 4

← C++ typing practice