Fix compilation on Windows
switch to std::sort and a lambda
use unique_ptr and throw an exception if allocation fails