typestar

Sets & uniqueness in C++

std::set stores each value once, sorted, and its insert reports whether it did anything.

#include <set>
#include <vector>

int unique_count(const std::vector<int> &values) {
    std::set<int> seen(values.begin(), values.end());
    auto [pos, inserted] = seen.insert(42);
    if (!inserted) {                  // 42 was already in the set
        seen.erase(pos);
    }
    return static_cast<int>(seen.size());
}

How it works

  1. Constructing from begin() and end() deduplicates the vector in one shot.
  2. insert returns a pair; structured bindings name it [pos, inserted].
  3. When inserted is false the value was already present, and erase(pos) removes it.
  4. size() counts distinct values, so duplicates in the input never inflate it.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
296
Tokens
86
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 3 of 3 in Containers, step 9 of 27 in Language basics.

← Previous Next →