我使用for循环和if-else语句尝试按字母顺序对书籍的标题进行排序。但是,我在returnlistofBooks方法下面临一些错误。有什么方法可以解决这个问题吗?
voidBookshelf::voidBookshelf(vector <Book*> listofBooks){
this->listofBooks = listofBooks;
}
void voidBookshelf::addBook()
{
int ID;
string Title;
string Author;
for (int i = 1; i <= 5; i++)
{
cout << "Book#"<< i << ":" << endl;
cout << "Enter an ID:";
cin >> ID;
cout << "Enter a title:";
cin >> Title;
cout << "Enter an author:";
cin >> Author;
Book *mybook = new Book(ID, Title, Author); //book object
listofBooks.push_back(mybook);
}
}
void returnListofBooks(int count, string name)
{
Book temp;
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count - i; j++)
{
if (books[j].author > books[j + 1].author)
{
//swapping the instances themselves, but still comparing by the member.
temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
int main(){
voidBookshelf * myBookshelf = new voidBookshelf;
myBookshelf->addBook();
myBookshelf->returnListofBooks();
return 0;
}
答案 0 :(得分:0)
你可以在这里查看排序功能!它非常简单! 去: http://www.cplusplus.com/articles/NhA0RXSz/
答案 1 :(得分:0)
允许排序的简单方法是在类中重载operator<
:
class Book
{
public:
bool operator< (const Book& b)
{
return author < b.author;
}
private:
std::string author;
};
如果要按其他字段排序,则需要编写自定义比较运算符:
class Book
{
std::string title;
friend bool order_by_title(const Book& a, const Book& b);
};
bool order_by_title(const& Book a, const Book& b)
{
return a.title < b.title;
}
std::vector<Book> library;
//...
std::sort(library.begin(), library.end(), order_by_title);