繁体   English   中英

如何通过其不同的属性对对象的 CLASS (不是结构)进行排序?

[英]how to sort A CLASS (not a struct) of objects by its different attributes?

编辑这里是我的代码:

class Book{
private:
int Serialnumber;
string Author; // I also have getters and setters for them
}
class Library{
vector<Book> inventory; // I added some books in the vector Inventory
}

我还有两个类的 2 个 header 和 2.cpp 文件。 在 each.cpp 文件中包含两个头文件,并在 each.cpp 文件中声明这两个类,以便我可以访问它们。 我现在需要对我的 vector<> 库存进行排序。 我需要 2 个函数,一个用于按序列号对它们进行排序,另一个用于按作者姓名对它们进行排序。

在 c++ 中 class 和结构之间没有显着差异。 基本上,所有区别都在于程序员的感知和默认访问权限,因此您可以简单地通过 function std::sort对它们进行排序并为其编写 2 个不同的比较器

所以我的实现看起来像这样(注意:您可以轻松地将 class 替换为结构)

class book //your custom class
{
private:
    string author;
    int pages;
public: 
    book(const string &str, int num): author(str), pages(num) {} 
    friend bool pages_compare(const book& lhs, const book& rhs); //friend comparator. If your fields are public, you may remove "friendship"
    friend bool author_compare(const book& lhs, const book& rhs);//friend comparator. If your fields are public, you may remove "friendship"
    friend void print(const book& arg);
};

bool pages_compare(const book& lhs, const book& rhs) // func for sorting by pages count
{
    return lhs.pages < rhs.pages;
}

bool author_compare(const book& lhs, const book& rhs) // func for sorting by author name
{
    return lhs.author < rhs.author;
}

void print(const book& arg) // custom printing
{
    cout << '{' << arg.author << ", " << arg.pages << "} ";
}

int main()
{
    book book0{"aurelius", 10};
    book book1{"bbbbbb", 5};
    book book2{"ccccc", 15};
    book book3{"au", 100};
    vector<book> arr = {book0, book1, book2, book3};
    sort(arr.begin(), arr.end(), pages_compare); // sort by page count
    for(auto &i: arr) // print
        print(i); // {bbbbbb, 5} {aurelius, 10} {ccccc, 15} {au, 100} 
    cout << '\n';
    sort(arr.begin(), arr.end(), author_compare); // sort by author name
    for(auto &i: arr) // print
        print(i); // {au, 100} {aurelius, 10} {bbbbbb, 5} {ccccc, 15} 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM