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

时间:2019-02-12 02:38:20

标签: c++ class hyperlink containers

在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;
}

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

1 个答案:

答案 0 :(得分:1)

这是你要去的地方吗?

#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";
}