stdmap - Adding element into C++ std::map inserts only one key -
i created simple library program, store map of book objects , quantity. add books map further able rent book, etc.
the problem in code, method called createlib
inserts 1 book object map. why that? how solve this? doing wrong here? thanks.
#include <iostream> #include <string> #include <map> using namespace std; class author { public: string name; author (){} author(string n){name = n;} }; class book { public: author author; string title; static int id; book (author a, string t){author = a, title = t; id ++;} }; int book::id = 0; struct comapare { bool operator() (const book& k1, const book& k2) { return k2.id < k1.id; } }; class library { public: map<book, int, comapare> books; void createlib() { author a1("bruce eckel"); book b1(a1, "thinking in java"); book b2(a1, "thinking in c++"); books.insert(std::make_pair(b1, 10)); books.insert(std::make_pair(b2, 2)); std::cout << books.size() << "\n"; } }; int main() { library l; l.createlib(); return 0; }
edit:
here's working version:
#include <iostream> #include <string> #include <map> using namespace std; class author { public: string name; author () {} author(string n) { name = n; } }; class book { public: author author; string title; static int id; int rid; book (author a, string t) { author = a, title = t; id ++, rid = id; } }; int book::id = 0; struct comapare { bool operator() (const book& k1, const book& k2) { return k2.rid < k1.rid; } }; class library { public: map<book, int, comapare> books; void createlib() { author a1("bruce eckel"); book b1(a1, "thinking in java"); book b2(a1, "thinking in c++"); books.insert(std::make_pair(b1, 10)); books.insert(std::make_pair(b2, 2)); std::cout << books.size() << "\n"; ( std::map<book, int, comapare>::const_iterator iter = books.begin(); iter != books.end(); ++iter ) cout << iter->first.title << "\t\t" << iter->second << '\n'; } }; int main() { library l; l.createlib(); return 0; }
the problem id
same instances of book
class.
you need two id
members: 1 static member increase, , 1 non-static member actual book id , assigned static id.
Comments
Post a Comment