C ++程序,用于对任何数据类型的变量进行排序
我们得到了不同数据类型的值,例如它可以是整数,浮点数,字符串,布尔值等类型,并且任务是使用一种通用方法或函数对任何数据类型的变量进行排序并显示结果。
在C++中,我们可以使用std::sort对C++标准模板库(STL)中可用的任何类型的数组进行排序。默认情况下,sort函数按升序对数组元素进行排序。Sort()函数接受三个参数-
数组列表中的开始元素,即您要从何处开始排序
在数组列表中结束元素,即直到您希望完成排序为止
通过将greater()函数传递为降序排列,将sort函数的默认设置更改为降序。
示例
Input-: int arr[] = { 2, 1, 5, 4, 6, 3}
Output-: 1, 2, 3, 4, 5, 6
Input-: float arr[] = { 30.0, 21.1, 29.0, 45.0}
Output-: 21.1, 29.0, 30.0, 45.0
Input-: string str = {"nhooo.com is best", "nhooo.com", "www.nhooo.com"}
Output-: nhooo.com nhooo.com is best www.nhooo.com
以下程序中使用的方法如下-
输入不同数据类型的变量,例如整数,浮点数,字符串等。
应用sort()将对任何类型的数组的元素进行排序的函数
打印结果
算法
Start
Step 1-> create template class for operating upon different type of data Template <class T>
Step 2-> Create function to display the sorted array of any data type
void print(T arr[], int size)
Loop For size_t i = 0 and i < size and ++i
print arr[i]
End
Step 3-> In main() Declare variable for size of an array int num = 6
Create an array of type integer int arr[num] = { 10, 90, 1, 2, 3 }
Call the sort function sort(arr, arr + num)
Call the print function print(arr, num)
Create an array of type string string str[num] = { "nhooo.com is best", "nhooo.com", "www.nhooo.com" }
Call the sort function sort(str, str + num)
Call the print function print(str, num)
Create an array of type float float float_arr[num] = { 32.0, 12.76, 10.00 }
Call the sort function sort(float_arr, float_arr+num)
Call the print function print(float_arr, num)
Stop示例
#include <bits/stdc++.h>
using namespace std;
//创建模板类的变量
template <class T>
void print(T arr[], int size) {
for (size_t i = 0; i < size; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main() {
int num = 6;
int arr[num] = { 10, 90, 1, 2, 3 };
sort(arr, arr + num);
print(arr, num);
string str[num] = { "nhooo.com is best", "nhooo.com", "www.nhooo.com" };
sort(str, str + num);
print(str, num);
float float_arr[num] = { 32.0, 12.76, 10.00 };
sort(float_arr, float_arr+num);
print(float_arr, num);
return 0;
}输出结果
0 1 2 3 10 90 nhooo.com nhooo.com is best www.nhooo.com 10 12.76 32