Search code examples
c++c++11stl-algorithm

Std::copy and std::ostream_iterator to use overloading function to print values


I am wondering how to use std::copy to use overloading operator of my class. For example to print vector of type int we can use something like this

std::vector<int> vec{ -1, 4, 70, -5, 34, 21, 2, 58, 0 , 34 , 27 , 4 };
std::copy( vec.begin(), vec.end(), std::ostream_iterator<int>( std::cout, " "));

But say I have class Employee and overloading operator <<

class Employee
{

public:
    Employee( const string _name, const string _last, const int _sal ):
        name(_name),
        lastname(_last),
        salary(_sal )
    {

    }
friend ostream& operator<<(ostream&os,  Employee&obj )
{
    return os << obj.name << " "<< obj.salary;
}

private:
    std::string name;
    std::string lastname;
    int salary;

};

Then how would I use std::copy to use ostream_iterator to print name of employee and salary example

 int main()
{
    std::vector<Employee> staff
     {
         {"tim", "sim", 1000 },
         {"dave", "ark", 2000 },
         {"kate", "Greg", 2000 },
         {"miller", "jane", 1000 },
         {"wht", "Up", 2000 }

     };

 std::copy( begin( staff), end(staff), std::ostream_iterator<Employee>( cout, " ")); // How to use this line ???
 return 0;
}

When I type above line I got compiler error invalid operands to binary expression


Solution

  • std::ostream_iterator::operator= takes its parameter as const&. Internally, this will use operator<< to output each value into the stream.

    But the parameter is const, so it can't be passed into your operator<<! A const& doesn't bind to a &. That's why the compiler is complaining. You will have to mark it const&:

    friend ostream& operator<<(ostream&os,  const Employee& obj )
    {
        return os << obj.name << " "<< obj.salary;
    }
    

    That's also good practice: You are not going to modify obj, so there is no reason why you don't mark it as const.