我如何将<vector>
用于对象数组,需要通过构造函数给出值?例如,带有名称的类,年龄需要通过构造函数Student(string n, int a ) { name = n , age = a }
获取信息。
所有数据都将通过键盘提供..
答案 0 :(得分:0)
这是一个程序的示例代码,能够使用向量获取和存储学生列表的名称和年龄。之后,它打印存储的信息。我使用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;
}
答案 1 :(得分:0)
可以使用initializer-list直接构建vector
名学生:
std::vector<Student> students{
{ "John", 22 },
{ "Melissa", 19 }
};
要稍后添加学生,可以使用成员函数emplace_back()
,它只是将其参数转发给Student
构造函数:
students.emplace_back( "Andy", 23 );
Pre C ++ 11必须使用成员函数push_back()
:
students.push_back( Student( "Andy", 23 ) );
可以在链接的参考页面上找到更多用法示例。