[英]how to sort the null objects in a dynamically allocated array of objects, so that the null objects are in the back of the array c++
我有一個動態分配的對象數組。 某些數組由對象填充,而其他部分為null。 當我使用冒泡排序對數組中的對象進行排序時,它會正確排序,但是null的數組部分位於填充的數組部分的前面。 有什么方法可以將空對象推到數組的后面而不是前面?
數組中發生的情況的圖片:
| null | null | null | object | object |
我想要數組的圖片:
| object| object | null | null | null |
這是我的氣泡排序代碼:
::bubbleSort()
{
bool flag = true;
obj temp;
int j = 0;
while(flag)
{
flag = false;
j++;
for(int i = 0; i < (max - j); i++)
{
if(arr[i] > arr[i + 1])
{
temp = arr[i];
arr[i]= arr[i+1];
arr[i+1] = temp;
flag = true;
}
}
}
}
這是我定義我的arr的方式:
private:
obj *arr;
然后在我的構造函數中
max = 25
arr = new obj[max];
您可以將std::sort
與自定義比較器一起使用:
std::sort(std::begin(arr), std::end(arr), [](auto *p1, auto *p2) {
if (p1 == nullptr) {
return false;
}
if (p2 == nullptr) {
return true;
}
return *p1 < *p2;
});
假設您的自定義類型定義了operator<
。 當然,您可以使用其他任何喜歡的東西進行比較。
如果必須實現自己的排序算法,則仍然可以將比較器函數的主體內聯到排序代碼的中間。
如果要查找的函數可能是std :: partition ,如果您想要的只是在后面加上null。 如果還需要對其他值進行排序 ,則std :: sort是正確的選擇。 兩者都允許您定義比較,以定義排序或分區順序,從而允許您自定義元素的排序方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.