C++ 程序用来对任何数据类型的变量来进行排序
我们提供了不同数据类型的值,如整型、浮点、字符串、布尔值等,我们的任务是使用一种通用方法或函数对任何数据类型的变量进行排序,并显示结果。
在 C++ 中,我们可以使用 std::sort 来对 C++ 标准模板库 (STL) 中可用的任何类型的数组进行排序。sort 函数默认按照升序对数组元素进行排序。Sort() 函数接受三个参数 -
数组列表中的起始元素,即从何处开始进行排序
数组列表中的结束元素,即要完成排序操作的位置
通过传递 greater() 函数将排序默认设置为降序。
示例
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 = {"tutorials point is best", "tutorials point", "www.tutorialspoint.com"}
Output-: tutorials point tutorials point is best www.tutorialspoint.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] = { "tutorials point is best", "tutorials point", "www.tutorialspoint.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;
// creating variable of template class
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] = { "tutorials point is best", "tutorials point", "www.tutorialspoint.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 tutorials point tutorials point is best www.tutorialspoint.com 10 12.76 32
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP