C++ 数组排序:使用 std::sort 函数
"C++ 数组排序:使用 std::sort 函数"\n\n您可以使用标准库中的sort函数来对数组进行排序。首先,您需要包含头文件<algorithm>来使用sort函数。然后,调用sort函数,并传入数组的起始地址和结束地址作为参数,即可完成排序。\n\n以下是使用C++代码对数组进行排序的示例:\n\ncpp\n#include <iostream>\n#include <algorithm>\n\nint main() {\n int a[10] = {10, 23, 45, 6, 7, 22, 33, 65, 3, 4};\n int size = sizeof(a) / sizeof(a[0]);\n\n std::sort(a, a + size);\n\n std::cout << \"排序后的数组:\";\n for (int i = 0; i < size; i++) {\n std::cout << a[i] << \" \" ;\n }\n std::cout << std::endl;\n\n return 0;\n}\n\n\n运行上述代码,输出结果为:\n\n\n排序后的数组:3 4 6 7 10 22 23 33 45 65\n\n\n注意,std::sort函数默认按照升序进行排序。如果您想要按照降序排序,可以使用std::greater<int>()作为第三个参数传递给sort函数,如下所示:\n\ncpp\nstd::sort(a, a + size, std::greater<int>());\n
原文地址: https://www.cveoy.top/t/topic/pI78 著作权归作者所有。请勿转载和采集!