Home > Back-end >  How to iterate through a returned custom class and print it's members
How to iterate through a returned custom class and print it's members

Time:12-09

I don't know how to print a returned value of a custom object.

#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

class Person{
private:
    string name;
    int age; 
public:
    Person(){
    };

    Person(string name, int age){
       this->name = name; 
       this->age = age; 
    }

    string getName(){
        return name; 
    }
};

class listOfPeople{
private:
    vector <Person> myList;
public:
    void fillTheList(Person p){
        myList.push_back(p);
    }

    Person findPerson(string name){
        for(Person p : myList){
            if(p.getName() == name) {
                return p; // returns a person
            }
        }
        return {};
    }
};

int main(){
   Person p1("Vitalik Buterin", 30); 
   Person p2("Elon musk", 50); 
   listOfPeople L; 
   L.fillTheList(p1); 
   L.fillTheList(p2); 
   Person p = L.findPerson("Vitalik"); //  I don't know what to do here (I want to print Vitalik's information, the full name and age)
   return 0; 
}

I don't know how to print the informations of the returned value. I tried different things but can't get the right logic.

CodePudding user response:

you just need

 std::cout << p.name << " is " << p.age <<'/n';

CodePudding user response:

Boost.PFR a.k.a. "magic get" could be one option if you are willing to turn Person into an aggregate:

#include <iostream>
#include <string>

#include "boost/pfr.hpp"

struct Person {
    std::string name;
    int age;
};

int main() {
    Person p{"Foo Bar", 85};

    std::cout << boost::pfr::io(p) << '\n';
}

Output

{"Foo Bar", 85}

Demo

CodePudding user response:

You can add a toString() function in the person class that returns a string with the object properties and then print it using:

// inside person
std::string toString() {
return this->name   " age: "   std::to_string(this->age);
}
std::cout << p.toString();

By adding this function to your class, every time you need to print the properties of person, just call toString().

You could also add implementation to the operator <<, you can search how.

  • Related