C++ 图书管理系统:数据结构设计与排序

本文将介绍如何使用 C++ 开发一个简单的图书管理系统,该系统能够存储、排序并展示图书信息。

1. 数据结构设计

为了表示图书信息,我们可以使用 C++ 中的结构体(struct):

struct Book {
    string title;   // 书名
    string author;  // 作者
    string date;    // 出版日期
};

2. 读取图书信息

首先,需要从用户输入中读取图书信息。假设用户会输入图书数量以及每本图书的书名、作者和出版日期。可以使用以下代码实现:

int n;  // 图书数量
Book books[100];    // 图书数组

// 读入图书信息
cin >> n;
for (int i = 0; i < n; i++) {
    cin >> books[i].title >> books[i].author >> books[i].date;
}

3. 按出版日期排序

为了按出版日期升序排序图书信息,可以使用 C++ 标准库中的 sort 函数以及自定义的比较函数。比较函数用来比较两个 Book 结构体的出版日期。

// 按照出版日期升序排序
sort(books, books + n, [](const Book& a, const Book& b) {
    return a.date < b.date;
});

4. 输出图书信息

最后,按照排序后的顺序输出所有图书信息。

// 输出图书信息
for (int i = 0; i < n; i++) {
    cout << books[i].title << ' ' << books[i].author << ' ' << books[i].date << endl;
}

完整代码:

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

struct Book {
    string title;   // 书名
    string author;  // 作者
    string date;    // 出版日期
};

int main() {
    int n;  // 图书数量
    Book books[100];    // 图书数组

    // 读入图书信息
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> books[i].title >> books[i].author >> books[i].date;
    }

    // 按照出版日期升序排序
    sort(books, books + n, [](const Book& a, const Book& b) {
        return a.date < b.date;
    });

    // 输出图书信息
    for (int i = 0; i < n; i++) {
        cout << books[i].title << ' ' << books[i].author << ' ' << books[i].date << endl;
    }
    return 0;
}

示例:

输入:

3 The Hitchhiker's Guide to the Galaxy Douglas Adams 1979-05-12 The Lord of the Rings J. R. R. Tolkien 1954-07-29 Harry Potter and the Sorcerer's Stone J. K. Rowling 1997-06-26

输出:

The Lord of the Rings J. R. R. Tolkien 1954-07-29 The Hitchhiker's Guide to the Galaxy Douglas Adams 1979-05-12 Harry Potter and the Sorcerer's Stone J. K. Rowling 1997-06-26

总结

本文介绍了如何使用 C++ 开发一个简单的图书管理系统,包括数据结构设计、排序算法以及代码示例。通过使用结构体和快速排序算法,可以轻松实现按出版日期升序排序的图书信息展示。


原文地址: https://www.cveoy.top/t/topic/ojKP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录