c++for-loopvector

How to count duplicates in a vector (C++)


I was working through an exercise in C++ Primer. Actually, I refined my first version. Problem is I not only want to detect duplications in a vector, but also how many times they were duplicated. I'm having trouble with the latter.

Here is my code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {

vector<int> nums{1,3,1,5,7,8,9,7};

sort(nums.begin(), nums.end());

for(unsigned int i = 0; i != nums.size(); ++i){
if(nums[i] == nums[i + 1]){
    cout << nums[i] << " is a duplicated number" << endl;
    }
}



return 0;

}

EDIT: Also just noticed my logic is flawed. If a number appears more than twice it will print out multiple times it's a duplicate. Which is redundant.


Solution

  • You were almost there, here is my suggested solution:

    live

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main() {
    
    vector<int> nums{1,3,1,5,7,8,9,7};
    
    sort(nums.begin(), nums.end());
    
    for(auto it = std::cbegin(nums); it != std::cend(nums); ) {  
    
        int dups = std::count(it, std::cend(nums), *it);
        if ( dups > 1 )
            cout << *it << " is a duplicated number, times: " << dups << endl;
        for(auto last = *it;*++it == last;);
    }
    
    return 0;
    
    }