I am working on a personal project and I have a bookshelf class and book class. I am implementing some functions and right now I'm implementing a remove_book function that takes a parameter of the title of the book they want removed from the bookshelf.
However I dont know how I would implement that. As an argument you can use any string. You will use the function get_title to compare the used argument with titles of elements in the vector and if such an element exists you can remove it from the vector.
I want to avoid loops as much as possible and use some STL algorithms like remove and then erase. How would this function be implemented in the best way?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Bookshelf {
public:
Bookshelf() {}
class Book {
private:
string title{};
string author{};
int pages{};
public:
Book(string const& t, string const& a, int const p)
: title{t}, author{a}, pages{p}
{}
string get_title() const {
return title;
}
void print() const {
cout << title << ", " << author << ", " << pages << endl;
}
};
void add_book(Book const& b) {
bookshelf.push_back(b);
}
void remove_book(string const& choice, vector<Book>& books) {
// remove(books.begin(), books.end(), ????)
}
void print_bookshelf() const {
for (const auto& e : bookshelf) {
e.print(); // this will print out our current vector and if we change
// it will change,
// instead of creating a copy which is memory consuming
}
}
private:
vector<Book> bookshelf{};
};
int main() {
Bookshelf::Book book_1("Hej", "Me", 100);
Bookshelf::Book book_2("Yo", "Me", 150);
Bookshelf bookshelf_1;
book_1.print();
bookshelf_1.add_book(book_1);
bookshelf_1.add_book(book_2);
bookshelf_1.print_bookshelf();
return 0;
}