I have the following code that finds first duplicate in a vector of integers:
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int find_duplicate(const vector<int> &v)
{
unordered_set<int> numbers;
for(const auto num : v)
{
if (numbers.count(num) > 0)
{
return num;
}
else
{
numbers.insert(num);
}
}
return -1;
}
int main()
{
std::vector<int> v = {1, 3, 4, 5, 3, 2, 3, 6, 2};
cout << find_duplicate(v);
return 0;
}
I am wondering if there is a more concise way of writing this using C++ std library algorithms?
find_duplicate should not modify the input vector nor make a copy of it.