Calvin
Calvin

Reputation: 45

C++ : How can I push values into a vector only if that value isn't stored in the vector already?

If for example, I was just pushing 200 random numbers into a vector, how can I ensure that duplicates will not be pushed in?

Upvotes: 3

Views: 2205

Answers (3)

lamandy
lamandy

Reputation: 982

If the random numbers are integer and within a relatively small range, you can try this: You want N unique random numbers from M possible values whereby M >= N

  1. create a container containing one of each of the unique random number
  2. shuffle the container
  3. take the first N from the container and insert to your vector

If M is much bigger than N (like between 0 and rand_max), then you should just check for repetition before insert and repeat until your container size reaches 200. If using vector is not mandatory, I will suggest using std::set instead since it ensures unique values by default.

Upvotes: 1

miradham
miradham

Reputation: 2345

You need to check if the vector already contains the value, if not the push new value, i.e.

std::vector<int>::iterator it;
it = find (myvector.begin(), myvector.end(), newvalue);
if (it == myvector.end()) {
    // newvalue is not found
}

But this could be costly since find method would be checking every value inside myvector. Instead using set or map data structure can be more efficient.

Upvotes: 2

Monza
Monza

Reputation: 755

seems like a map could be a helpful structure instead of a Vector. If you must stick to a Vector then you need to divide your task into two parts; duplication detection and then insertion. Again, your could insert into a map and then read that out into the Vector. In either case the problem is - intrinsically - two problems. Good luck!

Upvotes: 1

Related Questions