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
- Constructing from
begin()andend()deduplicates the vector in one shot. insertreturns a pair; structured bindings name it[pos, inserted].- When
insertedis false the value was already present, anderase(pos)removes it. size()counts distinct values, so duplicates in the input never inflate it.
Keywords and builtins used here
autoconstifintreturnstatic_castunique_count
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.
Step 3 of 3 in Containers, step 9 of 27 in Language basics.