Shr*_*ram 1 c++ sorting memory-management heap-memory dynamic-arrays
我们知道,当使用连续的内存块时,我们可以轻松地获得一个迭代器(在此处&arra[0]
或arra
),并将迭代器传递给std :: sort。
例如:
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);
Run Code Online (Sandbox Code Playgroud)
现在,如果我有一个堆分配的数组,请像下面这样说arr
:
int len;
len = 100;
int* arr = new int[len];
for (int i = 0; i < len; i++) {
arr[i] = rand() % 32000;
}
Run Code Online (Sandbox Code Playgroud)
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?
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);
Run Code Online (Sandbox Code Playgroud)
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.