How do I return a vector of all books sorting by title in alphabetical order? I created a vector called book which consist of the book title, ID and author but I just need to sort and print the title.
if you just want to print the titles alphabetically, the returnListofBook function doesn't need to return a vector<Book *>, it just need to return a set<string>...
and the returnListofBook function need to be granted friendship in the Book class
1 2 3 4 5 6 7 8 9
set<string> returnListofBook(vector<Book *> myBook) // #include<set>
{
set<string> titles;
for(auto item: mybook)
{
titles.insert(item->title); // i guess the Book class has a title data member
}
return titles;
}
after this function, you'll get a collection of titles ordered alphabetically
@qishuhao @Thomas1965 Thank you so much for your help. I managed to run the program with no errors now. Also, is there any way whereby i create a bookshelf object and calling the addbook method and allowing the user to input the detail of each book and store it into the vector 'Book'?
void Bookshelf::addBook(int id, string title, string author)
{
Book *book = new Book(id, title, author);
// Not sure what the name of the vector with the books is.
YourBookVector.push_back(book);
}
int main()
{
cout << "Enter an ID:";
cin >> id;
cout << "Enter a title:";
cin >> title;
cout << "Enter an author:";
cin >> author;
Bookshelf myBookshelf;
myBookshelf.addBook(id, title, author);
return 0;
You need to instantiate the vector first, like what you did in line 9.
1 2
vector<Book*> vBook;
vBook.push_back(myBook);
I would make a vector a parameter of the addBook function.
1 2 3 4
void Bookshelf::addBook(int ID, string Title, string Author, vector<Book*> vBook)
{
// do your stuff here
}
Make sure to delete the dynamically allocated memory!
1 2 3
// C++11 range based for loop
for(auto b: vBook)
delete b;
The reason why ID, Title and Author are undefined is because they don't exist in the scope of main(). Just make them variables in main and that should fix them being undefined.
To explicitly define a default constructor do
1 2
// C++11 default constructor, just learnt this recently
Book() = default;
a default constructor is a constructor without parameters.
1 2 3 4 5 6 7 8 9 10 11
class Bookshelf
{
public:
Bookshelf(); // declaration of the default constructor
};
Bookshelf::Bookshelf() // definition / implementation of the default constructor
{
// initialization of variables and other stuff here
}
@Thomas1965 Thanks. I understand more about default constructor now. I thought i wasn't supposed to use set as my lecturer has not taught us this topic yet but he said it's fine if I could do it.