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

更新日期: 20-Dec-2019

1k+ 瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.