How can i know if a sorted vector has duplicate values or not in C++ -


i don't want change vector or create new vector duplicates removed. want check duplicates, like:

{90, 80, 70, 60, 50, 40, 30, 20, 10, 10} -> true {90, 89, 88, 87, 86, 85, 84, 83, 82, 81} -> false 

since vector sorted, can check if 2 adjacent elements equals :

for (auto = vec.begin() + 1; != vec.end(); ++it) {   if (vec[it] == vec[it - 1])   {     // duplicate     return true;   } } // no duplicate return false; 

you use std::adjacent_find returns iterator first element of first duplicate in vector:

auto = std::adjacent_find(vec.begin(), vec.end()); if (it == vec.end()) {   // no duplicate   return false; } // duplicate return true; 

Comments

Popular posts from this blog

html - Difficulties with background-image property -

visual studio code - What does the isShellCommand property actually do and how should you use it? -

ios - Segue not passing data between ViewControllers -