Problem: I need to get a random element for a container and also delete it from that container. Container does not need to be sorted. I dont care about the order.
You have the solution, and it seems perfectly fine. The idiomatic way to write it in C++ is not to create another class (and please don't inherit from std::vector), but just to write a function:
template
void remove_at(std::vector& v, typename std::vector::size_type n)
{
std::swap(v[n], v.back());
v.pop_back();
}
Usage:
remove_at(v, 42);
This offers the same exception guarantee as std::swap
.
Now if you want to return the object, and you have access to a C++11 compiler, you can do it the following way. The difficult part is to provide the basic exception guarantee in all cases:
template
T remove_at(std::vector&v, typename std::vector::size_type n)
{
T ans = std::move_if_noexcept(v[n]);
v[n] = std::move_if_noexcept(v.back());
v.pop_back();
return ans;
}
Indeed, you don't want the vector to be left in an invalid state if an exception is thrown during a move operation.