It is not fully clear, if your values in the std::vector
are sorted or allowed to be sorted. This makes a difference.
Anyway, I will show you 2 solutions.
First. We will sort the values in the vector. Then we will iterate over all values. We will increase the duplicate counter, if the current value is equal to the previous value and if we did not increase the counter for this value already.
This we will determine with a simple boolean comparison of the previous and current value.
Very simple and straightforward.
The second solution, and this is my prefereed solution, uses the standard approach for such questions. I will count all occurences of different integers. For that you can use a std::map
or std::unordered_map
. The important part here is the functionality of the index operator.
This
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
With counter[i]++;
, either the value i exists already and its counter will be incremented, or, if the value i was not existing before, an entry will be created, and the coounter incremented.
At the ned, we will just count all counters with a value > 1, because thats the meaning of or dupe in this context.
Please see:
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
int countduplicate1(std::vector<int> number) {
// Sort a vector, so that all duplicates are adjacent
std::sort(number.begin(), number.end());
// The result. Counter for duplicates
int counter{};
bool newNumber{ true };
// Go through all digits and check, if duplicate
for (size_t i{}; i < number.size(); ++i) {
// If duplicate, but was not already counted before
if ((i > 0) && newNumber && (number[i] == number[i - 1]))
++counter;
newNumber = ((i > 0) && (number[i] != number[i - 1]));
}
return counter;
}
int countduplicate2(std::vector<int> number) {
// Counter for occurence of an integer
std::map<int, size_t> counter{};
// Count all different integer
for (int i : number) counter[i]++;
// Duplicate means that an integer is avaliable more than once
return std::count_if(counter.begin(), counter.end(), [](const std::pair<int, size_t>& c) {return c.second > 1; });
}
int main() {
std::vector<int> vect{ 1,3,3,4,4,4,7,9,9,9,8 };
std::cout << countduplicate1(vect) << '\n';
std::cout << countduplicate2(vect) << '\n';
return 0;
}