首页 > 解决方案 > 项目中的排序算法实现

问题描述

我有这个 C++ 工作 C++ 项目。我真的是编程新手,学习 C++。我很想在这个项目中添加一个排序功能。例如,根据学生 ID/书籍 ID 进行排序。我应该如何解决问题。或此类项目的任何其他功能。按日期排序:按截止日期对任务进行排序。按学生编号排序。按字母顺序排序:按任务名称的字母顺序对任务进行排序。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>

using namespace std;

class Book {
    int BookID;
    int BookISBN;
    char BookName[20];
    char BookAuthor[50];
    int BookRackNo;
    int BookSlotNo;
    float BookCost;
    char date[10];

  public:
    void getData ();
    void showData ();
    int getBookId () {
        return BookID;
}}
b;

void Book::getData ()
{
    cout << "\n\nEnter Book Details......\n";
    cout << "Enter Book ID : ";
    cin >> BookID;
    cout << "Enter Book ISBN : ";
    cin >> BookISBN;
    cout << "Enter Book Name : ";
    cin.ignore ();
    cin.getline (BookName, 20);
    cout << "Enter Book Author : ";
    cin.ignore ();
    cin.getline (BookAuthor, 50);
    cout << "Enter Book Location Rack #: ";
    cin >> BookRackNo;
    cout << "Enter Book Location Slot #: ";
    cin >> BookSlotNo;
    cout << "Enter Book Cost: $ ";
    cin >> BookCost;
    cout << "Enter Book Purchase Date MM/DD/YYYY: ";
    cin >> date;
    cout << endl;
}

void Book::showData ()
{
    cout << "\n\n.......Book Details......\n";
    cout << "Book ID : " << BookID << endl;
    cout << "Book ISBN : " << BookISBN << endl;
    cout << "Book Name : " << BookName << endl;
    cout << "Book Author : " << BookAuthor << endl;
    cout << "Book Location Rack #: " << BookRackNo << endl;
    cout << "Book Location Slot #: " << BookSlotNo << endl;
    cout << "Book Cost: $ " << BookCost << endl;
    cout << "Book Purchase Date: " << date << endl;
    cout << endl;
}

void addBook ()
{
    ofstream fout;
    fout.open ("Book.dat", ios::binary | ios::out | ios::app);
    b.getData ();
    fout.write ((char *) &b, sizeof (b));
    fout.close ();
    cout << "\n\nData Successfully Saved....\n";
}

void displayBook ()
{
    ifstream fin;
    fin.open ("Book.dat", ios::in | ios::binary);
    while (fin.read ((char *) &b, sizeof (b))) {
        b.showData ();
    }
    fin.close ();
//cout << "\n\nData Reading from File Successfully Done....\n";
}

void searchBook ()
{
    int n, flag = 0;
    ifstream fin;
    fin.open ("Book.dat", ios::in | ios::binary);
    cout << "Enter Book ID you want to search : ";
    cin >> n;

    while (fin.read ((char *) &b, sizeof (b))) {
        if (n == b.getBookId ()) {
            cout << "The details of Book ID " << n << " are:\n";
            b.showData ();
            flag++;
        }
    }
    fin.close ();
    if (flag == 0)
        cout << "The Book Id " << n << " not found....\n\n";
    // cout << "\n\nData Reading from File Successfully Done....\n";
}

void deleteBook ()
{
    int n, flag = 0, result;
    ifstream fin;
    ofstream fout, tout;

    fin.open ("Book.dat", ios::in | ios::binary);
    fout.open ("TempBook.dat", ios::out | ios::app | ios::binary);
    tout.open ("TrashBook.dat", ios::out | ios::app | ios::binary);

    cout << "Enter Book ID you want to move to Trash : ";
    cin >> n;

    while (fin.read ((char *) &b, sizeof (b))) {
        if (n == b.getBookId ()) {
            cout << "The Following Book ID " << n <<
                " has been moved to Trash:\n";
            b.showData ();
            tout.write ((char *) &b, sizeof (b));
            flag++;
        } else {
            fout.write ((char *) &b, sizeof (b));
        }
    }
    fout.close ();
    tout.close ();
    fin.close ();
    if (flag == 0)
        cout << "The Book ID " << n << " not found....\n\n";
    remove ("Book.dat");
    result = rename ("tempBook.dat", "Book.dat");
    cout << result;
}

void getTrashBook ()
{
    ifstream fin;
    fin.open ("TrashBook.dat", ios::in | ios::binary);
    while (fin.read ((char *) &b, sizeof (b))) {
        b.showData ();
    }
    fin.close ();
    //cout << "\n\nData Reading from Trash File Successfully Done....\n";
}

void modifyBookData ()
{
    int n, flag = 0, pos;
    fstream fio;

    fio.open ("Book.dat", ios::in | ios::out | ios::binary);

    cout << "Enter Book ID you want to Modify : ";
    cin >> n;

    while (fio.read ((char *) &b, sizeof (b))) {
        pos = fio.tellg ();
        if (n == b.getBookId ()) {
            cout << "The Following Book ID " << n <<
                " will be modified with new data:\n";
            b.showData ();
            cout << "\n\n Enter the New Details....\n";
            b.getData ();
            const __int64 Z = pos - static_cast < __int64 > (sizeof (b));
            fio.seekg (Z);
            //fio.seekg(pos-sizeof(b));
            fio.write ((char *) &b, sizeof (b));
            flag++;
        }
    }
    fio.close ();

    if (flag == 0)
        cout << "The Book ID " << n << " not found....\n\n";
}

void project ()
{
    int ch;
    do {
        system ("cls");
        cout << "======================================"
                "====================================\n";
        cout << "...............UNIVERSITY LIBRARY "
                "DATABASE MANAGEMENT SYSTEM..............\n";
        cout << "======================================"
                "====================================\n";
        cout << "0. Exit from Program\n";
        cout << "1. Add New Book\n";
        cout << "2. List all Books\n";
        cout << "3. Search a Book \n";
        cout << "4. Delete a Book \n";
        cout << "5. List of Deleted Books\n";
        cout << "6. Modify Details of a Book\n";
        cout << "Enter your choice : ";
        cin >> ch;
        system ("cls");
        switch (ch) {
        case 1:
            addBook ();
            break;
        case 2:
            displayBook ();
            break;
        case 3:
            searchBook ();
            break;
        case 4:
            deleteBook ();
            break;
        case 5:
            getTrashBook ();
            break;
        case 6:
            modifyBookData ();
            break;
        }
        system ("pause");
    } while (ch);
}

int main ()
{
    project ();
}

标签: c++algorithm

解决方案


C++ 标准库已经有一个用于排序序列或容器的实现:std::sort

std::sort()<对于已经具有 less ( ) 比较运算符的类型(例如 for intor ) ,可以“开箱即用” std::string。但也可以提供一种适用于自定义类型的自己的比较方法。例如,如果要对 s 的 std::vector 进行排序,可以Book这样做:

#include <algorithm> // provides std::sort
#include <vector>    // provides std::vector

...

std::vector<Books> all_books;

// ... (Fill all_books with some data here.)

std::sort(all_books.begin(), all_books.end(),
          // lambda expression for comparison
          [](const Book& a, const Book& b)
          {
              return a.BookID < b.BookID;
          }
);

这将对Books的向量进行排序BookID

备选方案:

如果你想实现运算符<for Book,你也可以这样做。这将消除为std::sort. 一个可能的实现 - 再次排序BookId- 可能是:

bool Book::operator< (const Book& other) const
{
  return BookID < other.BookID;
}

这将允许您像这样使用排序:

std::vector<Books> all_books;

// ... (Fill all_books with some data here.)

std::sort(all_books.begin(), all_books.end());

奖金回合:

也可以按多个数据成员排序。例如,如果有人想先排序BookCost,如果成本等于BookID,那么比较方法可能如下所示:

std::sort(all_books.begin(), all_books.end(),
          // lambda expression for comparison
          [](const Book& a, const Book& b)
          {
              // Try BookCost as first criterion.
              if (a.BookCost < b.BookCost)
                  return true;
              if (a.BookCost > b.BookCost)
                  return false;
              // BookCost is equal for both books
              // (or at least one BookCost is NaN,
              //  but let's not get into that here).
              // Let's use the BookID as tie-breaker.
              return a.BookID < b.BookID;
          }
);

推荐阅读