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

时间:2015-06-04 09:14:10

标签: c++ stdmap

我创建了一个简单的库程序,我在其中存储了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;
}

1 个答案:

答案 0 :(得分:4)

问题是id类的所有实例Book都相同。

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