#include #include #include #include #include using namespace std; struct Book { string name{}; double weight{}; }; class Bookshelf { private: vector shelf; double max_weight; double current_weight() const { return std::accumulate(begin(shelf), end(shelf), 0.0, [] (double lhs, Book const& rhs) { return lhs + rhs.weight; }); } public: Bookshelf(double max_weight) : shelf{}, max_weight{max_weight} {} void put_book(Book const& book) { if ( current_weight() + book.weight <= max_weight ) { shelf.push_back(book); } } string to_string() const { stringstream strs{""}; for ( auto const& book : shelf ) { strs << book.name << " "; } return strs.str(); } }; int main() { Bookshelf bookshelf{5.0}; bookshelf.put_book( Book{"The Hobbit", 0.4} ); bookshelf.put_book( Book{"Learning Python", 3.6} ); bookshelf.put_book( Book{"C++ Primer", 2.0} ); bookshelf.put_book( Book{"Learning C++", 2.2} ); bookshelf.put_book( Book{"C++ Templates", 2.0} ); bookshelf.put_book( Book{"The Pickaxe", 0.9} ); cout << bookshelf.to_string() << endl; return 0; }