Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การจัดเรียงโครงสร้าง (Structure Sorting) ใน C++

นี่คือวิธีจัดเรียง (sorting) ตามเงื่อนไขบนตัวแปรสมาชิกของโครงสร้าง (structure) ใน C++ ตัวอย่างใช้โครงสร้างชื่อ book เก็บชื่อ จำนวนหน้า และราคา จัดเรียงตามราคา

เพื่อเปรียบเทียบโครงสร้างสองตัว ต้องกำหนดฟังก์ชันเปรียบเทียบ ฟังก์ชันนี้ใช้ภายใน sort function เพื่อจัดเรียงค่า

ตัวอย่าง

#include <iostream>
#include <algorithm>
using namespace std;

struct book {
  string title;
  int pages;
  float price;
};

bool compareBook(book b1, book b2) {
  if (b1.price < b2.price)
    return true;
  return false;
}

main() {
  book book_arr[5];
  book_arr[0].title = "C Programming";
  book_arr[0].pages = 260;
  book_arr[0].price = 450;
  book_arr[1].title = "DBMS Guide";
  book_arr[1].pages = 850;
  book_arr[1].price = 775;
  book_arr[2].title = "Learn C++";
  book_arr[2].pages = 350;
  book_arr[2].price = 520;
  book_arr[3].title = "Data Structures";
  book_arr[3].pages = 380;
  book_arr[3].price = 430;
  book_arr[4].title = "Learn Python";
  book_arr[4].pages = 500;
  book_arr[4].price = 300;
  sort(book_arr, book_arr + 5, compareBook);
  for (int i = 0; i < 5; i++) {
    cout << book_arr[i].title << "\t\t" << book_arr[i].pages << "\t\t" << book_arr[i].price << endl;
  }
}

ผลลัพธ์

Learn Python    500     300
Data Structures 380     430
C Programming   260     450
Learn C++       350     520
DBMS Guide      850     775