Click here to Skip to main content
16,015,629 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So for the love of everything, can someone tell me how to print a vector of class objects? I've looked everywhere I can think - which is not many places considering I'm on a Chromebook from my school.

//EDIT: Preferably in a function.
//EDIT_2: Thanks to any help given!

What I have tried:

Turned Google upside down and looked through my tome of C++ knowledge.
Posted
Updated 12-Sep-23 11:58am
v3

1 solution

One possibility would be to overload the << operator for ostream in the class as a friend. This would allow you to simply output the class with std::cout.
C++
class MyClass {
public:
    friend std::ostream& operator<<(std::ostream& os, class MyClass& m)
    {
        // TODO: output your data to stream
        return os;
    }
};


//Edit:
If you want to output a vector with classes you can first use the suggestion for the member variables from your class. Since it is not known how the class looks like it is not possible to say how this works in detail. After that an overload for ostream is also necessary for the output of the vector. Instead of putting the overload in the class you could also write a function or a template for the operator. In any case the operator << should output the data as ostream. By the way, you can also copy() the elements of a vector into the stream instead of writing a loop for it yourself.
 
Share this answer
 
v2
Comments
Brennon Nevels 9-Sep-23 19:19pm    
So I would then just add the for loop where the comment is?
merano99 9-Sep-23 19:28pm    
yes :-)
Brennon Nevels 9-Sep-23 19:39pm    
Awesome, thanks- so far its almost worked with a template class and a place to insert the vector I wish to print though I need a second argument so time to find that. Thanks, mate!
CPallini 11-Sep-23 3:06am    
5.
merano99 11-Sep-23 3:23am    
thx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900