ในโปรแกรม C++ นี้ เราจะสาธิตการจัดเรียงคอนเทนเนอร์ใน STL โดยใช้ std::list และฟังก์ชัน sort() ซึ่งเป็นวิธีที่ง่ายและมีประสิทธิภาพสำหรับการจัดเรียงข้อมูลในลิสต์
ฟังก์ชันและคำอธิบาย
- l.push_back() – ใช้แทรกองค์ประกอบเข้า list จากท้าย (ไม่ใช่จากหน้าตามที่ระบุในต้นฉบับ)
- l.sort() – จัดเรียงองค์ประกอบใน list ให้เป็นลำดับจากน้อยไปมาก
โค้ดตัวอย่าง (โปรแกรมโต้ตอบแบบเมนู)
#include <iostream>
#include <list>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
list<int> l;
list<int>::iterator it;
int c, i;
while (true) {
cout << "1.Insert Element to the list" << endl;
cout << "2.Display the List (sorted)" << endl;
cout << "3.Exit" << endl;
cout << "Enter your Choice: ";
cin >> c;
switch(c) {
case 1:
cout << "Enter value to be inserted: ";
cin >> i;
l.push_back(i);
break;
case 2:
l.sort();
cout << "Elements of the List: ";
for (it = l.begin(); it != l.end(); it++)
cout << *it << " ";
cout << endl;
break;
case 3:
exit(0);
default:
cout << "Wrong Choice" << endl;
}
}
return 0;
}
ตัวอย่างผลลัพธ์
1.Insert Element to the list 2.Display the List 3.Exit Enter your Choice: 1 Enter value to be inserted: 7 Enter your Choice: 1 Enter value to be inserted: 10 Enter your Choice: 1 Enter value to be inserted: 6 Enter your Choice: 1 Enter value to be inserted: 4 Enter your Choice: 2 Elements of the List: 4 6 7 10 Enter your Choice: 3 Exit code: 0
คำอธิบายเพิ่มเติม: std::list::sort() ใช้การจัดเรียงแบบ Merge Sort ซึ่งมีความซับซ้อน O(n log n) และรักษาความเสถียร (stable sort) นอกจากนี้ list ยังมี merge() สำหรับรวมลิสต์ที่จัดเรียงแล้ว และ unique() สำหรับลบค่าซ้ำได้อีกด้วย