STD SET problem, will not let me print set

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
Have you overloaded operator<< to be able to print out a Book with cout?
For my Book class I did overload it, I have no problem printing out those objects when I use it with cout.
This is the exact error that shows :

Invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'const value_type' (aka 'const Book'))
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
1
2
3
4
5
6
7
8
9
10
11
12
ostream& operator<<(ostream& os, Book& b){
    os << "Title: " << b.title << endl << "Authors: " ;
    for(int i=0; i<b.authors.size(); i++){
        os << b.authors.at(i);
        if(i < (b.authors.size())-1)
            os << ", ";
        else
            os << endl;
    }
    os << "Publisher: " << b.publisher << endl << "Year Of Publication: " << b.yearOfPublication << endl << endl << endl;
    return os;
}
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
I did try it and it gave me same error :(
I'm stumped, my friendly.
Hopefully someone else will be able to help.
I'm interested in the answer myself.
Topic archived. No new replies allowed.