Operator overloading <<, how to print vector

Hi all,

I'm asked to define the operator << to print the data that is stored in two vectors of an object. This is my class:

1
2
3
4
5
6
7
8
9
10
11
12
class Name_pairs{
public:
	void read_names();	// get names
	void read_ages();	// get corresponding ages
	void sort();

	vector<string> get_names() const;
	vector<double> get_ages() const;
private:
	vector<string> name;
	vector<double> age;
};


This is my operator overloading function thus far:

1
2
3
4
ostream& operator<<(ostream& os, const Name_pairs& np)
{
	return os<<'('<<
}



How do I output these vectors using this function? I reckon I must use a loop, but I'm unsure how this would affect the output stream. The objective is to be able to use cout<<(Name_pairs object) to print the name pairs.

edit: I figured that I'd need some way to acces the vectors stored, so I added two member functions that return the vectors. However << doesn't accept vectors, so it hasn't helped much.
Last edited on
When I was playing around with vectors, I made a function for vector output:

1
2
3
4
5
6
7
8
9
10
void outputVecStr( strVector v )
{
	strVecIter vIter = v.begin();

	while( vIter != v.end() )
	{
		std::cout << *vIter << '\n';
		++vIter;
	}
}


Combine this with your << overload.

Are you sure you do it like:
return os<<'('<<

I've always done something like the following:
1
2
3
4
5
6
ostream& operator<<(ostream& os, const Name_pairs& np)
{
        os << "Output something: " <<  np.useClass << '\n';

	return os;
}
One of the previous assignments was to output the vector using a member function print():

1
2
3
4
5
6
void Name_pairs::print()
{
	for(int i=0; i<name.size(); i++){
		cout<<"("<<name[i]<<", "<<age[i]<<")\n";
	}
}


But I'm supposed to replace that with using << overload.
I see that you store something in os before returning it, would this then perhaps be possible?:

1
2
3
	for(int i=0; i<name.size(); i++){
		os<<"("<<name[i]<<", "<<age[i]<<")\n";
	}


So as to stack up all the pairs? I'll see if I can get that to work.

edit: It worked! Wonderful, thanks a ton. :)
Last edited on
Topic archived. No new replies allowed.