Search code examples
c++sortingmemory-managementheap-memorydynamic-arrays

Can I use std::sort on heap allocated raw arrays?


We know that when using a contiguous block of memory we can easily get an iterator (here &arra[0] or arra) and pass the iterators to std::sort.

for instance:

int arra[100];
    for (int i = 0; i < 100; i++) {
        arra[i] = rand() % 32000;
    }
    for (int i = 0; i < len; i++)std::cout << arra[i]<<" ";
    std::sort(arra,arra+100);

Now if I have a heap allocated array, say, like arr here:

int len;
    len = 100;
    int* arr = new int[len];
    for (int i = 0; i < len; i++) {
        arr[i] = rand() % 32000;
    }

I don't know whether I can get an iterator for this array, so can I use std::sort for this array at all? if not, are there any workarounds to using std::sort on such an array?


Solution

  • Pointers do meet criteria of RandomAccessIterator which is required by std::sort. It doesn't matter if they point to stack memory or heap memory, as long as they point to the same (contiguous) array. So you can simply use:

    std::sort(arr, arr + len);
    

    This being said, std::vector is probably a better choice for allocating an array on the heap. It will save you the headache of managing memory on your own.