Reputation: 131
I'm trying to use the << operator to output vectors that are private members of my class.
The compiler won't let me access the vectors directly as they are private, but it also won't let me access public member functions that return the vectors.
How do I make the << operator output all the contents of a private member vector?
This is my class:
class Name_pairs
{
public:
Name_pairs (){}
//....
vector<string> Names (){return names; }
vector<double> Ages (){return ages; }
vector<double> Sorted_ages (){return sorted_ages;}
private:
//....
vector<string> names;
vector<double> ages;
vector<double> sorted_ages;
};
This is the overloaded << function:
ostream& operator<<(ostream& os, const Name_pairs & n)
{
return os<< n.Names(); //won't let me access
return os<< n.names.size(); //won't let me access
}
This is the print function that I'm trying to replace by overloading the << function:
void Name_pairs:: print_name_age ()
{
cout << endl << endl;
cout << "These names and ages are now sorted" << endl;
for(int index = 0; index < names.size(); ++index)
{
cout << "index " << index << ": " << names[index]<< " is age: " << sorted_ages[index] <<endl;
}
}
Upvotes: 2
Views: 5001
Reputation: 96845
n.Names()
returns a vector and you can't print vectors directly through a standard operator <<
method. You have to iterate through the vector and print its elements.
std::ostream& operator<<(std::ostream& os, const Name_pairs& n)
{
if (!os.good())
return os;
auto names = n.Names();
std::copy(names.begin(), names.end(),
std::ostream_iterator<std::string>(os));
return os;
}
Upvotes: 2
Reputation: 4012
The line
return os<< n.Names(); //won't let me access
doesn't work, because you're trying to write a whole vector at once, instead of it's elements, and ostream
doesn't provide an overloaded operator <<
for the std::vector
. The solution is just writing elements from the vector
, that's being returned by this function.
for(int i=0;i<n.Names().size();i++)
cout << n.Names()[i];
As a side note: you probably don't want to use your version with large vectors, since (unless your compiler is smart enough to make the function inline), will consume a lot of time to return the whole vector. Try returning a const reference to the vector, instead of the vector itself.
Upvotes: 1