May 7, 2018 at 11:07pm UTC
So I know when you want to print out a STD set of objects , you need an iterator and iterate through it. I have done that and dereferenced the iterator as well to print it out but Xcode keeps telling me that theres an error when I use (*it) and it changes it to &it which prints out the address, not what I want.
1 2 3
for (set<Book>::iterator it=b.begin(); it != b.end();++it)
cout<<(*it) << endl;
Last edited on May 8, 2018 at 2:18am UTC
May 7, 2018 at 11:39pm UTC
Have you overloaded operator<< to be able to print out a Book with cout?
May 8, 2018 at 12:38am UTC
For my Book class I did overload it, I have no problem printing out those objects when I use it with cout.
May 8, 2018 at 12:39am UTC
This is the exact error that shows :
Invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'const value_type' (aka 'const Book'))
May 8, 2018 at 12:45am UTC
Post the overloaded operator<< for Book.
There's nothing wrong with your loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <set>
using namespace std;
class Book {
int n;
public :
Book(int n) : n(n) {}
int getn() const { return n; }
};
bool operator <(const Book& a, const Book& b) {
return a.getn() < b.getn();
}
ostream& operator <<(ostream& os, const Book& b) {
return os << b.getn();
}
int main() {
set<Book> b {1, 2, 3};
for (set<Book>::iterator it = b.begin(); it != b.end(); ++it)
cout << *it << '\n' ;
// Alternatively:
//for (const auto& x: b) cout << x << '\n';
}
Last edited on May 8, 2018 at 12:50am UTC
May 8, 2018 at 12:57am UTC
I don't know what to say. Try my example from the previous post and see if it works.
This is just a little rewrite, It won't solve anything. :-(
1 2 3 4 5 6 7 8 9
ostream& operator <<(ostream& os, const Book& b){
os << "Title: " << b.title
<< "\nAuthors: " << b.authors[0];
for (size_t i = 1; i < b.authors.size(); i++)
os << ", " << b.authors[i];
os << "\nPublisher: " << b.publisher
<< "\nYear Of Publication: " << b.yearOfPublication << "\n\n\n" ;
return os;
}
Last edited on May 8, 2018 at 12:57am UTC
May 8, 2018 at 1:01am UTC
I did try it and it gave me same error :(
May 8, 2018 at 1:10am UTC
I'm stumped, my friendly.
Hopefully someone else will be able to help.
I'm interested in the answer myself.