mardi 25 janvier 2022

Finding the max lengths of strings to format a table output

I want to find the max length of specific attributes from a vector of Person objects.

Below is an example of a Person object:

Person::Person(string first_name, string last_name, int the_age){
     first = first_name;
     last = last_name;
     age = the_age;
} 

I have a vector that stores Person objects, and I must print all the people out in a table, like so:

First Name  Last Name     Age
----------  ------------  ----
John        Cool-Johnson  15
Paul        Bob           1000
2 people

I need to find the max length of each attribute of a Person in order to grow each column according to the maximum length of name or age. How can I do this?

So far, I have tried lambdas using this code:

unsigned int max_name = *max_element(generate(people.begin(),people.end(), [](Person a){return a.getFirstName()})).size();

But I am not sure if this even works at all.

I must use <iomanip>, but I have no clue how it works.

Is there a better way?

Aucun commentaire:

Enregistrer un commentaire