Reputation: 45
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
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
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
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
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