1

这是我的主要内容:

#include <iostream>
#include <vector>
#include "Book.h"

using namespace std;

vector<Book> removeDuplicates(vector<Book> oldbookvector)
{
    vector<Book> newbookvector;
    vector<string> booknames;

    for(vector<Book>::size_type i = 0; i < oldbookvector.size(); i ++){
        booknames.push_back(oldbookvector[i].bookname());
    }

    vector<Book>::iterator it;
    for(vector<Book>::size_type i = 0; i < oldbookvector.size(); i ++){
        //If it find a value then it returns the first element
        it = find(newbookvector.begin(),newbookvector.end(), oldbookvector[i]);
        if(it == newbookvector.end()){
            booknames.push_back(oldbookvector[i].bookname());
        }
    }

    return newbookvector;
}

int main(int argc, const char * argv[])
{
    vector<Book> books;
    vector<Book> newbooks;

    books.push_back(Book("The C Programming Language", 1980));
    books.push_back(Book("Javascript: The Good Parts", 2008));
    books.push_back(Book("Accelerated C++: Pratical Programming by Example", 2000));
    books.push_back(Book("Scala for the Impatient", 2012));
    books.push_back(Book("The C Programming Language", 1980));
    books.push_back(Book("Javascript: The Good Parts", 2008));
    books.push_back(Book("Accelerated C++: Pratical Programming by Example", 2000));
    books.push_back(Book("Scala for the Impatient", 2012));

    cout << &books[2] << endl;
    cout << books[2].bookname() << endl;

    //Test to make sure book class was working
    Book stuff = Book("The Book about stuff", 1998);
    cout << stuff.bookname() << endl;
    cout << stuff.bookyear() << endl;

    stuff.printBook();

    //newbooks = removeDuplicates(books);

    //Print out the vector without duplicates
    for(vector<Book>::size_type i = 0; i < newbooks.size(); i ++){
        cout << newbooks[i].bookname() << newbooks[i].bookyear() << "\t";
    }

    return 0;
}

我在 algorithm.cc 中不断收到错误消息,显示“二进制表达式的操作数无效('Book' 和 'const Book')”。我认为它来自 find()。我很确定问题是迭代器没有遍历书籍

这是我的书课

#ifndef Question2_Book_h
#define Question2_Book_h
using namespace std;

class Book{
public:
    Book();

    Book(string n, int y){
        name = n;
        year = y;
    }

    string bookname(){
        return name;
    }
    int bookyear(){
        return year;
    }

    void printBook(){
        cout << name << ", " << year << endl;
    }

private:
    string name;
    int year;
};
#endif
4

1 回答 1

1
  • std::find位于<algorithm>所以首先你应该包括那个标题。

  • 为了找到 a Book,您需要定义operator==(std::find使用它来确定是否Book找到 a ),否则您如何知道是否找到了 a Book

例子

bool operator==(const Book& b1, const Book& b2)
{
    // 2 books are equal if they have the same name, you could also compare years
    // if you want
    return b1.bookname() == b2.bookname();
} 

另外,请注意我正在使用const. 为了使用上述内容,您需要修复代码的一部分(注意我添加了一个const):

string bookname() const {
     return name;
}
于 2012-10-04T23:07:26.380 回答