C++创建动态数组后如何进行排序

avatar
作者
筋斗云
阅读量:0

在C++中,可以使用标准库中的std::sort函数来对动态数组进行排序。首先,需要包含<algorithm>头文件来使用std::sort函数。

接下来,假设已经创建了一个动态数组arr,可以使用以下方式对该动态数组进行排序:

#include <iostream> #include <algorithm>  int main() {     int size;     std::cout << "Enter the size of the array: ";     std::cin >> size;      int* arr = new int[size];      std::cout << "Enter elements of the array: ";     for (int i = 0; i < size; ++i) {         std::cin >> arr[i];     }      std::sort(arr, arr + size);      std::cout << "Sorted array: ";     for (int i = 0; i < size; ++i) {         std::cout << arr[i] << " ";     }      delete[] arr;      return 0; } 

在这个例子中,用户首先输入了动态数组的大小,然后输入了数组中的元素。接着使用std::sort函数对动态数组进行排序,并输出排序后的数组。最后,使用delete[]释放动态数组的内存。

值得注意的是,对于动态数组的排序,使用std::sort函数是效率较高的方法。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!