ในส่วนนี้เราจะมาดูกันว่าเราสามารถจัดเรียงอาร์เรย์หรือรายการที่เชื่อมโยงโดยใช้ไลบรารีมาตรฐานของ C ++ ได้อย่างไร ใน C ++ มีไลบรารีต่างๆ มากมายที่สามารถใช้เพื่อวัตถุประสงค์ที่แตกต่างกัน การคัดแยกเป็นหนึ่งในนั้น
ฟังก์ชัน C++ std::list::sort() จัดเรียงองค์ประกอบของรายการโดยเรียงลำดับจากน้อยไปมาก ลำดับขององค์ประกอบที่เท่ากันจะถูกรักษาไว้ ใช้โอเปอเรเตอร์<เพื่อเปรียบเทียบ
ตัวอย่าง
#include <iostream>
#include <list>
using namespace std;
int main(void) {
list<int> l = {1, 4, 2, 5, 3};
cout << "Contents of list before sort operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
l.sort();
cout << "Contents of list after sort operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
return 0;
} ผลลัพธ์
Contents of list before sort operation 1 4 2 5 3 Contents of list after sort operation 1 2 3 4 5