0

I am surprise that there is no std::is_unique in the algoritm part of the STL.

I've workaround the value with std::unique_copy but I found that poor because it performs memory allocation when I really just need to know if there are duplicated values.

I am aware of the alternative solution consisting of iterating over while inserting into an std::set to find duplicate but same story.

Is there an efficient, elegant (i.e : one liner using only std algorithms) solution ?

std::vector<std::string> elements = { "foo", "bar", "foo"} ;

std::vector<std::string> uniquified;
std::unique_copy(cbegin(elements),cend(elements), std::back_inserter(uniquified));
   if (uniquified.size() != elements.size())
       return "Elements are not unique";
sandwood
  • 2,038
  • 20
  • 38
  • Use a different container, where this is a no-brainer? Like `std::multiset`? Otherwise it is logically impossible to do this without some kind of memory allocation. You cannot defeat the fundamental laws of physics and logic in our shared universe. I'm fond of saying that C++ can do anything, but I'm always lying when I say that. That's something that even C++ cannot do -- violate the laws of physics and logic. – Sam Varshavchik Nov 22 '20 at 16:27
  • Indeed i need to check uniqueness based on others conditions , so in many cases I will never perform this check, therefore the nominal scenario is : there is no duplicate, and even if It's ok. Only on seldom cases the check is required. So I think a non sorted container suits most of the cases – sandwood Nov 22 '20 at 16:31
  • Then, again, you'll have to deal with additional memory allocation, of some sort, when this needs to happen. – Sam Varshavchik Nov 22 '20 at 16:33
  • @SamVarshavchik: Well, it *can* be done without additional allocation; there's an obvious O(n^2) algorithm... – Nate Eldredge Nov 22 '20 at 16:42

0 Answers0