Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting duplicates with set

Tags:

c++

set

I am working with data that shouldn't pop up twice. If it does, it should detect it and invoke a function handling that.

Currently, I am pushing some data to a vector and before insertion, it should check if the data is already contained in that vector. At the moment, this is not very effective, e.g

for (int i = 0; i < myVector.size() ; i++) 
{
  if ( myVector[i] == data ) 
  {
             // invoke function
             return false;
  }
}

I know set is a special kind of vector which allows only unique data.

Is there another way to detect duplicate data being added (or at least attempting to add it) to the set?

like image 242
Darlyn Avatar asked Mar 21 '16 15:03

Darlyn


People also ask

How do you find duplicates in a set of data?

If you want to identify duplicates across the entire data set, then select the entire set. Navigate to the Home tab and select the Conditional Formatting button. In the Conditional Formatting menu, select Highlight Cells Rules. In the menu that pops up, select Duplicate Values.

Can you have duplicates in a set?

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.


1 Answers

First let's just be clear that a set is not a special kind of vector. It's a kind of container, orthogonal to vector, that happens to prevent duplicates.

You can detect duplicates by checking the return value from insert:

if(my_set.insert("value").second == false) { do_something_for_duplicate(); }
like image 119
Mark B Avatar answered Oct 16 '22 05:10

Mark B