[Solved] Group duplicate items in vector – c++ [closed]


You’re close. You already figured out your bounds problem, but consider what happens at the interface of clusters:

..2,2,3,3...
    ^ ^
    i i+1

You are going to enter the else (else if is unnecessary if the condition is the exact opposite of the original if) and forget to add that last 2. If there are no duplicates in the vector, such as

`{1,2,3,4}`

You are not going to add anything but empty clusters! So, you always want to add the number, rather you’re in a cluster or ending it. If you’re ending a cluster you also want to add it and clear.

for(int i = 0 ; i < sorted.size()-1 ; i++ ){
    cluster.push_back(sorted[i]);
    if ( sorted[i] != sorted[i+1]){
        clusters.push_back(cluster);
        cluster.clear();
    }
}

Finally, as @tobi303 mentioned the last element is missing. This is especially obvious with a list with a single element ({3}). Note the last cluster is not added in any case, whether if it’s a new single element at the end or just a final cluster.

So, once we exit the for we need one more check (not really) – if the cluster is empty that means the last element is not a part of it, and is a new one. Otherwise, the last cluster wasn’t added yet and you need to append the last element to it, and then add the cluster. I’m leaving this one up to you.

6

solved Group duplicate items in vector – c++ [closed]