tags:

views:

71

answers:

2

If I have a C++ set and iterator:

set<Person> personList;
set<Person>::const_iterator location;

How can I print out the contents of the set? They are all person objects, and I have overloaded operator<< for Person.

The line that errors is in a basic for loop:

cout << location

Netbeans gives:

proj.cpp:78: error: no match for ‘operator<<’ in ‘std::cout << location’

It looks like it wants an overload for the iterator's operator<<.

Basically, I am taking objects that used to be stored in an array format, but are now in a set. What is the equivalent to cout << array[i] for sets?

+3  A: 

You need to dereference the iterator:

 std::cout << *location;

The convention of using the indirection or dereferencing operator to get the referenced value for an iterator was chosen in analogy to pointers:

 person* p = &somePerson;
 std::cout << *p;
Georg Fritzsche
+1 for most direct answer to OP's question.
Billy ONeal
Oh, I see. This is also why the arrow operator allows me to access the object's fields. Thanks!
John Smith
+2  A: 

Why use a for loop when you can use an algorithm instead?

#include <iterator> //for std::ostream_iterator
#include <algorithm> //for std::copy
#include <iostream> //for std::cout

void foo()
{
    std::copy(
        personList.begin(),
        personList.end(),
        std::ostream_iterator(std::cout, " ")
    );
}

Note that this works with any pair of iterators, not only those from std::set<t>. std::copy will use your user-defined operator<< to print out every item inside the set using this single statement.

Billy ONeal
+1, I've never seen that before.
DeadMG
+1, I love proper STL advocacy :)
Kornel Kisielewicz