Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check std::vector has duplicates

I want to check if a vector of integers has any duplicates or not, and have to return true if it does. So I try to do something like this:

vector<int> uGuess = {1,2,3,3,4,5}
vector<int> a = uGuess;
sort(a.begin(), a.end());
bool d = unique(a.begin(), a.end());

And this will not work since unqiue cannot be assigned as a bool value. How should I proceed towards this? If I were to write a for loop to perform the same action, how should I do that?

like image 793
rrc Avatar asked Sep 28 '17 20:09

rrc


People also ask

How do I check if a vector has duplicates?

Generic function to find duplicates in vector :Create a Generic function to get the duplicate elements and their duplication count i.e. * Generic function to find duplicates elements in vector. for (auto it = countMap. begin() ; it !=

Can std :: vector have duplicates?

Yes, but sorting a vector modifies the original content.

Can vector have duplicates in C++?

The unique() function in C++ helps remove all the consecutive duplicate elements from the array or vector. This function cannot resize the vector after removing the duplicates, so we will need to resize our vector once the duplicates are removed. This function is available in the <algorithm.

How do you know if a vector is unique?

Proof (a) Suppose that 0 and 0 are both zero vectors in V . Then x + 0 = x and x + 0 = x, for all x ∈ V . Therefore, 0 = 0 + 0, as 0 is a zero vector, = 0 + 0 , by commutativity, = 0, as 0 is a zero vector. Hence, 0 = 0 , showing that the zero vector is unique.


1 Answers

The algorithm you're looking for is std::adjacent_find.

// The container must be sorted!
const std::vector<int> sortedVector = {1,2,3,3,4,5};
const bool hasDuplicates = std::adjacent_find(sortedVector.begin(), sortedVector.end()) != sortedVector.end();

Unlike std::unique, std::adjacent_find doesn't modify the container.

As a bonus, std::adjacent_find returns an iterator to the first element in the duplicate "pair":

const auto duplicate = std::adjacent_find(sortedVector.begin(), sortedVector.end());

if (duplicate != sortedVector.end())
    std::cout << "Duplicate element = " << *duplicate << "\n";
like image 71
Jan Holecek Avatar answered Sep 19 '22 15:09

Jan Holecek