Delete this number from the vector
You're probably doing too much work for this. Remember, for example, that deleting from the end of the vector is a lot faster than deleting from the front of the vector.
Since you don't care where in the vector your numbers are, you can speed things up by moving the number you want to delete to the end of the vector; e.g.
int take_from_vector(vector<int> &vec, size_t pos)
{
int rv = vec[pos];
swap(vec[pos], vec.back());
vec.pop_back();
return rv;
}
However, if you're generating just a few things, it is probably faster to use rejection sampling: you keep track of which numbers you've generated, then reject any repeats. e.g.
int generate_another_number(set<int> &already_generated, int bound)
{
while (true) {
int rv = rand() % bound;
auto pos = already_generated.insert(rv);
if (pos.second) { return rv; }
}
}
Depending on how many things you're generating, you might want to use unordered_set<int>
instead of set
. Or maybe even use vector
and just iterate over the vector to see if it contains the generated number.
P.S. consider using C++'s random number generation features, rather than the ancient rand()
function.