gpt4 book ai didi

c++ - 将 std::find 与自定义 Book 类一起使用

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:09:55 27 4
gpt4 key购买 nike

这是我的主要内容:

#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

最佳答案

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

  • 为了找到一个Book , 你需要定义 operator== ( std::find 用它来确定是否找到了 Book),否则你怎么知道你是否找到了 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;
}

关于c++ - 将 std::find 与自定义 Book 类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737171/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com