Question

I can use a set iterator and std::cout to display the elements stored in a multi-set but for learning process I want to do by ostream_iterator and it looks like I am bit clueless.
Here is what I did and What I am interested in doing

I have a class say class Student

class Student
{
private : 
    int age_;
    std::string name_;
    double marks_;

public :
    Student();

    Student(int age, string name, double marks):
        age_( age ),
        name_( name ),
        marks_( marks)
    {
    }

    int get_age() const 
    {
        return age_;
    }

    std::string get_name() const
    {
      return name_;
    }

    double get_marks() const
    {
        return marks_;
    }

};

I have stored all the objects of Student class in multi-set in ascending order of their age. example

class Compare
{
public:
     bool operator ()(Student s1,  Student s2)
     {
        return ( s1.getage() < s2.getage() );
     }

};

// ... then somewhere ...
std::multiset<Student, Compare > student_set;
Student A21( 21, " AVi", 49.5 );
Student A17( 17, " BLA", 67.0 );
Student A57( 57, " BLC", 41.0 );

bla bla bla .....
bla bla bla.....

student_set.insert( A21 );
student_set.insert( A17 );
bla bla bla .....
bla bla bla.....

Now I would like to display everything using ostream_iterator so that I will get

student.get_name() << student.get_age() << student.get_marks(); 

// no idea what to do here ??
std::ostream_iterator< ???? >output( std::cout, " " ); 

std::copy( student_set.begin(), student_set.end(), output );
Was it helpful?

Solution

You need to overload operator<< for your class, because that's what ostream_iterator calls when being assigned to.

Something like this:

std::ostream& operator<<(std::ostream& os, const Student& s)
{
    return os << get_name() << get_age() << get_marks(); // needs some formatting
}

And then you construct the iterator with Student as template argument:

std::ostream_iterator<Student> output( std::cout, " " );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top