Suppose I have a dynamic array that I want to sort, I could do
std::vector<int> v(100);
for (int i = 0; i < 100; i++) v[i] = rand();
std::sort(v.begin(), v.end());
but for performance critical code, the initialization overhead is unacceptable, more details at https://stackoverflow.com/a/7269088/3667089
I could also do
int *v = new int[100];
for (int i = 0; i < 100; i++) v[i] = rand();
std::sort(v, v + 100);
but having to manage memory ourselves is bound to memory leak in large codebases.
So it seems that the most feasible approach is
std::unique_ptr<int[]> v(new int[100]);
for (int i = 0; i < 100; i++) v[i] = rand();
std::sort(v, v + 100);
No initialization overhead nor need to worry about memory management, but this returns a long compilation error. Could someone let me know what I am doing wrong?
I am on Ubuntu 14.04, GCC as compiler.
EDIT: Change the code so the data is not already sorted