โจทย์
เราได้รับค่าของชนิดข้อมูลต่างๆ เช่น integer, float, string, bool ฯลฯ งานคือเรียงตัวแปรของชนิดข้อมูลใดๆ โดยใช้วิธีหรือฟังก์ชันร่วมเดียวกันและแสดงผลลัพธ์
ใน C++ เราสามารถใช้ std::sort เพื่อเรียงอาเรย์ประเภทใดก็ได้ซึ่งมีใน C++ standard template library (STL) โดยค่าเริ่มต้น sort function เรียงองค์ประกอบอาเรย์ในลำดับขึ้น Sort() function รับสามอาร์กิวเมนต์ -
- เริ่มต้นองค์ประกอบในรายการอาเรย์ คือจุดที่คุณต้องการเริ่มการเรียง
- สิ้นสุดองค์ประกอบในรายการอาเรย์ คือจุดที่คุณต้องการให้การเรียงสิ้นสุด
- เปลี่ยนการตั้งค่าเริ่มต้นของ sort function เป็นลำดับลงโดยส่ง greater() function เพื่อเรียงในลำดับลง
ตัวอย่าง
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
แนวทางที่ใช้ในโปรแกรมด้านล่าง
- รับตัวแปรของชนิดข้อมูลต่างๆ เช่น integer, float, string ฯลฯ
- ใช้ฟังก์ชัน sort() ที่จะเรียงองค์ประกอบของอาเรย์ประเภทใดก็ได้
- พิมพ์ผลลัพธ์
อัลกอริทึม
เริ่ม
ขั้นตอน 1 → สร้าง template class สำหรับทำงานกับชนิดข้อมูลต่างๆ
Template <class T>
ขั้นตอน 2 → สร้างฟังก์ชันแสดงอาเรย์ที่เรียงแล้วของชนิดข้อมูลใดๆ
void print(T arr[], int size)
วนลูป For size_t i = 0 ถึง size และ ++i
พิมพ์ arr[i]
จบวน
ขั้นตอน 3 → ใน main()
ประกาศตัวแปรขนาดอาเรย์ int num = 6
สร้างอาเรย์ประเภท integer int arr[num] = { 10, 90, 1, 2, 3 }
เรียกฟังก์ชัน sort(arr, arr + num)
เรียกฟังก์ชัน print(arr, num)
สร้างอาเรย์ประเภท string string str[num] = { "tutorials point is best", "tutorials point", "www.tutorialspoint.com" }
เรียกฟังก์ชัน sort(str, str + num)
เรียกฟังก์ชัน print(str, num)
สร้างอาเรย์ประเภท float float float_arr[num] = { 32.0, 12.76, 10.00 }
เรียกฟังก์ชัน sort(float_arr, float_arr+num)
เรียกฟังก์ชัน print(float_arr, num)
หยุด
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
// สร้างตัวแปร 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