【问题标题】:How to use <vector> with constructor如何将 <vector> 与构造函数一起使用
【发布时间】:2018-01-16 19:44:12
【问题描述】:

我如何将&lt;vector&gt; 用于对象数组,这些对象需要通过构造函数赋值?例如,具有 name,age 的类需要通过构造函数 Student(string n, int a ) { name = n , age = a } 获取包含信息的数组。

所有数据将通过键盘给出..

【问题讨论】:

  • 任何机会让我们知道该语言
  • C++ 。对不起
  • 好吧添加标签
  • 您的问题不清楚 - 再试一次
  • std::vector&lt;Student&gt; 有什么问题?

标签: c++ arrays class object vector


【解决方案1】:

这是一个程序示例代码,该程序能够使用向量获取和存储学生列表的姓名和年龄。之后,它会打印存储的信息。我使用的是MSVC作为编译器,所以如果你不在windows上,可以去掉system("pause")

#include <vector>
#include <string>
#include <iostream>

using namespace std;

class Student {
public:
    Student(string n, int a) : name(n), age(a) {}

    string GetName(void) { return name; }
    int GetAge(void) { return age; }

private:
    string name;
    int age;

};

int main(void) {
    vector<Student> students;

    unsigned int n;

    cout << "How many students are there?" << endl;
    cin >> n;

    for (unsigned int i = 0; i < n; ++i) {
        string name;
        int age;

        cout << endl << "Please give me the information of the student " << i + 1 << endl;

        cout << "What is the name of the student?" << endl;
        cin >> name;

        cout << "What is the age of the student?" << endl;
        cin >> age;

        students.push_back(Student(name, age));
    }

    cout << endl << "Printing information of the students" << endl << endl;

    for (unsigned int i = 0; i < n; ++i) {
        Student& student = students[i];

        cout << "Student " << i + 1 << " is " << student.GetName() << " and is " << student.GetAge() << " years old." << endl;
    }

    system("pause");

    return 0;
}

【讨论】:

  • 如果没有其他要问的,你可以接受我的回答,或者zett42的回答,它有更多的方式将元素推入向量中。
【解决方案2】:

可以使用initializer-list 直接构造学生的vector

std::vector<Student> students{
    { "John", 22 },
    { "Melissa", 19 }
};

稍后要添加学生,可以使用成员函数 emplace_back(),它只是将其参数转发给 Student 构造函数:

students.emplace_back( "Andy", 23 );

在 C++11 之前,必须使用成员函数 push_back()

students.push_back( Student( "Andy", 23 ) );

更多使用示例可以在链接的参考页面上找到。

【讨论】:

  • 谢谢,我需要一个带有键盘输入值的版本
  • @sebbyz 好吧,如果您需要有人为您完成作业,请寻找其他答案。
猜你喜欢
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
相关资源
最近更新 更多