将元素添加到 C++ std::map 仅插入一个键

Adding element into C++ std::map inserts only one key

我创建了一个简单的图书馆程序,我在其中存储了 Book 对象及其数量的映射。我想在地图上添加一些书籍,以便进一步租借书籍等

问题是在我的代码中,名为 createLib 的方法仅将一本书对象插入地图。这是为什么?如何解决这个问题?我在这里做错了什么?谢谢

#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;
}

编辑:

这是工作版本:

#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";
        for ( 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;
}

问题是 id 对于 Book class 的所有实例都是相同的。

您需要 两个 id 成员:一个您增加的静态成员,以及一个非静态成员,它是实际的图书 ID 并从静态 ID.