정수, 부동 소수점, 문자열, 부울 등의 유형이 될 수 있는 것과 같은 다양한 데이터 유형의 값이 제공되며 작업은 하나의 공통 메소드 또는 함수를 사용하여 모든 데이터 유형의 변수를 정렬하고 결과를 표시하는 것입니다.피>
C++에서는 std::sort를 사용하여 C++ 표준 템플릿 라이브러리(STL)에서 사용할 수 있는 모든 유형의 배열을 정렬할 수 있습니다. 기본적으로 정렬 기능은 배열 요소를 오름차순으로 정렬합니다. Sort() 함수는 세 개의 인수를 취합니다 -
배열 목록의 시작 요소, 즉 정렬을 시작하려는 위치부터
배열 목록의 끝 요소, 즉 정렬을 수행할 위치까지
내림차순으로 정렬하는 better() 함수를 전달하여 정렬 함수의 기본 설정을 내림차순으로 변경합니다.
예시
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