I would go for the most straightforward solution:
auto previous_first = 0;
auto is_first_iteration = true;
for (const auto& key_value : myMap) {
const auto& key = key_value.first;
const auto& value = key_value.second;
if (is_first_iteration || key.first != previous_first) {
is_first_iteration = false;
previous_first = key.first;
// do something here!
}
}
Here you just simply iterate over each element (and we rely on the property of std::map that elements are sorted. And pairs are sorted themselves by the first and then by the second element). On each step we remember the previous first element - if on this step it's the same we just skip this step.
@AndrewDurward points out that this problem can be solved in logarithmic time. This is true only partially. First, this problem can be solved in logarithmic time only in the best case. What if you have N elements and each of them has different first
? You have N elements in the answer and obviously, you cannot output N elements in logarithmic time.