Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to print elements of a vector of type Person class in c++

I created a class called person with two members name and age then I created two objects of that

class p1 and p2 and then I added them to a vector. I tried then to print them but could not.

this my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Person{
public: 
    string name; 
    int age; 
}; 



int main(){
    Person p; 
    vector <Person> vector; 
    p.name = "Vitalik"; 
    p.age = 29; 
    Person p2; 
    p2.name = "Bueterin"; 
    p2.age = 50; 
    vector.push_back(p); 
    vector.push_back(p2); 
    
    for(int i = 0; i < vector.size(); i++){
        cout << vector[i] << endl; 
    }

    

    return 0; 
}

I tried multiple ways to loop through the vector and print the elements but I keep getting this message:

 error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'std::__vector_base<Person, std::allocator<Person> >::value_type' (aka 'Person'))
        cout << vector[i] << endl; 

>Solution :

You can implement operator<< or just write something like this:

cout << vector[i].name << ": " << vector[i].age << endl;

cout doesn’t know how to print this object by default.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading