Vla_DOS

ListSortClasses

Mar 5th, 2022
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <list>
  5. using namespace std;
  6.  
  7. class BookFair {
  8. public:
  9.     string NameBook;
  10.     string Author;
  11.     double Price;
  12.     BookFair() {
  13.         NameBook = Author = Price = 0;
  14.     }
  15.    
  16.     BookFair(string NameBook, string Author, double Price) {
  17.         this->NameBook = NameBook;
  18.         this->Author = Author;
  19.         this->Price = Price;
  20.     }
  21.  
  22.     void Print() {
  23.         cout << "NameBook: " << NameBook << "\tAuthor: " << Author << "\tPrice: " << Price << endl;
  24.     }
  25. };
  26.  
  27. static void SortByNameBook(list<BookFair> &list) {
  28.     list.sort([](BookFair& l1, BookFair& l2) { return l1.NameBook < l2.NameBook; });
  29. }
  30. static void SortByAuthor(list<BookFair> &list) {
  31.     list.sort([](BookFair& l1, BookFair& l2) { return l1.Author < l2.Author; });
  32. }
  33. static void SortByPrice(list<BookFair> &list) {
  34.     list.sort([](BookFair& l1, BookFair& l2) { return l1.Price < l2.Price; });
  35. }
  36.  
  37.  
  38. int main() {
  39.     string path = "text.txt";
  40.     BookFair bf("a", "3", 3);
  41.    // bf.Print();
  42.  
  43.    /* ofstream fout;
  44.     fout.open(path, ofstream::app);
  45.  
  46.     if (!fout.is_open())
  47.     {
  48.         cout << "Error open!" << endl;
  49.     }
  50.     else {
  51.         fout.write((char*)&bf, sizeof(BookFair));
  52.     }
  53.     fout.close();*/
  54.     list<BookFair> l;
  55.  
  56.     ifstream fin;
  57.     fin.open(path);
  58.  
  59.     if (!fin.is_open())
  60.     {
  61.         cout << "Error open!" << endl;
  62.     }
  63.     else {
  64.         BookFair b;
  65.  
  66.         while (fin.read((char*)&b, sizeof(BookFair)))
  67.         {
  68.            // b.Print();
  69.             l.push_back(b);
  70.  
  71.         }
  72.         for (auto i : l)
  73.             cout << i.NameBook << "\t" << i.Author << "\t" << i.Price << "\t" << endl;
  74.         SortByNameBook(l);
  75.         cout << endl;
  76.         for (auto i : l)
  77.             cout << i.NameBook << "\t" << i.Author << "\t" << i.Price << "\t" << endl;
  78.  
  79.     }
  80.     fin.close();
  81. }
Advertisement
Add Comment
Please, Sign In to add comment