在我的代码中使用列表、成员函数和类是否正确

Is use of list, member functions, and classes correct in my code?

本文关键字:函数 是否 成员 代码 我的 列表      更新时间:2023-10-16

在用MATLAB编码后,我不得不回到C++。我错过了一些东西。无论如何,我写了一个代码来创建可扩展的人的名字、姓氏和年龄列表。通过可扩展,我的意思是,如果需要,以后可以创建更多条目。

它实例化了 5 人的名字、姓氏和年龄。我需要使其可扩展,并计算人员列表的平均年龄。我在代码中使用了列表。

#include <iostream>
#include <list>
int main() {
    // Create a list of first names and initialize it with 5 first names
    std::list<string> firstname(new string[] { "Brad", "John", "Neptune",    "Kuh", "Dhar", "Rock" });
    // Iterate over and display first names
    for (string val : firstname)
        std::cout << val << ",";
            std::cout << std::endl;
    // Create a list of last names and initialize it with 5 last  names
    std::list<string> lastname(new string[] { "Mish", "Jims", "Nepers", "Yho", "Har", "Ock" });
    // Iterate over and display first names
    for (string val2 : lastname)
        std::cout << val2 << ",";
            std::cout << std::endl;

    // Create an empty list of ages pf persons
    std::list<int> ages(5, {34, 56, 57, 91, 12});
    // Iterate over the list and display ages
    for (int val1 : ages)
        std::cout << val1 << ",";
        std::cout << std::endl;
    // Compute average age
    for (int jj=0; jj <5; jj++)
    agesum = age(jj) + age(jj+1);
    avage = agesum/(jj+1);
    return 0;
}

但是,它不会执行,并给出错误。您能否更正代码,并就正在发生的事情向我提供反馈?

这就是你想要的吗?

#include <string>
#include <iostream>
#include <vector>
int main(){
    std::vector<std::string> first_names {"Brad", "John", "Neptune", "Kuh", "Dhar", "Rock"};
    std::vector<std::string> last_names {"Mish", "Jims", "Nepers", "Yho", "Har", "Ock"};
    std::vector<int> ages {34, 56, 57, 91, 12};
    int avg_age = 0;
    for(int age : ages) avg_age += age;
    avg_age /= ages.size();

    if(first_names.size() == last_names.size()){
        for(int i = 0; i < first_names.size(); i++){
            std::cout << first_names[i] << " " << last_names[i] << "n";
        }
    }
    std::cout << "average age: " << avg_age << "n";
}