Normally you use move-semantics to avoid the copies (for non-trivial types). std::swap() handles that for you, though a single std::move() would work.
Here's my general function for swap-and-popping vectors:
//Swap-and-pop a specific element of a container, swapping the element with the element at the back of the container and then popping it off the stack.
//This does not preserve the order of the elements.
template<typename ContainerType>
void SwapAndPopAtIndex(ContainerType &container, size_t index)
{
//Don't swap the back element with itself, and also don't swap out of range.
/*
The (index+1) is to prevent the back element from swapping with itself.
This could be more clearly written as: if(index >= (container.size()-1))
...but since 'container.size()' is unsigned,
the -1 would accidentally loop it around if size() returns 0, which is a likely occurance.
*/
if((index+1) >= container.size())
return;
//Swap the element with the back element.
std::swap(container[index], container.back());
//Pop the back of the container, deleting our old element.
container.pop_back();
}
It does not preserve the order of elements.
The fact that it does not handle the case of desiring to remove the last element means this is less than a robust solution, as you end up having to write a conditional for every usage... I would recommend modifications to properly handle the case of popping the last element. Additionally, an assert for when the index is >= size would be more appropriate, as the desired goal is to fail in a non-silent manner when someone does something stupid (like try and remove an element outside of the bounds of the container). Furthermore, by handling the swap case in a saner manner, i.e. simply skipping it if we're the last element, we can call this function without requiring any additional checks. Whereas with your current one, you require a check to see if you're the last element (in which case you just pop) or call this method, which then does the same check AGAIN. Thus the solution below is probably more what you desire:
template<typename ContainerType>
void SwapAndPopAtIndex(ContainerType & container, size_t index)
{
// ensure that we're not attempting to access out of the bounds of the container.
assert(index < container.size());
//Swap the element with the back element, except in the case when we're the last element.
if (index + 1 != container.size())
std::swap(container[index], container.back());
//Pop the back of the container, deleting our old element.
container.pop_back();
}