我想從物件中找到特定屬性的最大vector長度Person。
下面是一個Person物件的例子:
Person::Person(string first_name, string last_name, int the_age){
first = first_name;
last = last_name;
age = the_age;
}
我有一個vector存盤Person物件的物件,我必須將所有人列印在一張桌子上,如下所示:
First Name Last Name Age
---------- ------------ ----
John Cool-Johnson 15
Paul Bob 1000
2 people
我需要找到 a 每個屬性的最大長度,Person以便根據nameor的最大長度增長每一列age。我怎樣才能做到這一點?
到目前為止,我已經使用以下代碼嘗試了 lambdas:
unsigned int max_name = *max_element(generate(people.begin(),people.end(), [](Person a){return a.getFirstName()})).size();
但我不確定這是否有效。
我必須使用<iomanip>,但我不知道它是如何作業的。
有沒有更好的辦法?
uj5u.com熱心網友回復:
你的使用std::max_element()是錯誤的。它需要 2 個迭代器作為輸入,您沒有提供給它。它需要看起來更像這樣:
auto max_name = max_element(
people.begin(), people.end(),
[](const Person &a, const Person &b){
return a.getFirstName().size() < b.getFirstName().size();
}
)->getFirstName().size();
在線演示
或者:
vector<string> names;
names.reserve(people.size());
for(const Person &p : people) {
names.push_back(p.getFirstName());
}
auto max_name = max_element(
names.begin(), names.end(),
[](const string &a, const string &b){
return a.size() < b.size();
}
)->size();
在線演示
但是,由于您可能還想對Last Name和Age列執行相同的操作,因此我建議people您簡單地手動回圈遍歷向量,并在進行程序中跟蹤最大長度,例如:
string::size_type max_fname = 10;
string::size_type max_lname = 9;
string::size_type max_age = 3;
for(const Person &p : people)
{
max_fname = max(max_fname, p.getFirstName().size());
max_lname = max(max_lname, p.getLastName().size());
max_age = max(max_age, to_string(p.getAge()).size());
}
然后您可以在表格中輸出所有內容,例如:
cout << left << setfill(' ');
cout << setw(max_fname) << "First Name" << " " << setw(max_lname) << "Last Name" << " " << setw(max_age) << "Age" << "\n";
cout << setfill('-');
cout << setw(max_fname) << "" << " " << setw(max_lname) << "" << " " << setw(max_age) << "" << "\n";
cout << setfill(' ');
for(const Person &p : people)
{
cout << setw(max_fname) << p.getFirstName() << " " << setw(max_lname) << p.getLastName() << " " << setw(max_age) << p.getAge() << "\n";
}
cout << people.size() << " people\n";
在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/421510.html
標籤:
