我正在学习矢量。我尝试实现一个打印向量的结构元素的代码,如下所示。互联网上的许多资源只教我一个简单的向量。当打印它时,我得到了表达。但是,任何提高代码质量和优雅性的建议都是开放的,尽管更改是基本的(在结构或循环中)。
非常感谢。
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
typedef struct _student {
string name;
int age;
vector <string> subject;
}student;
int _tmain(int argc, _TCHAR* argv[])
{
vector <student> x; //assmue at this point we do not know the number of students
student y;
//and I want to insert new information
y.name ="John";
y.age =9;
y.subject.push_back("biology");
y.subject.push_back("math");
y.subject.push_back("art");
x.push_back(y);
//get new information again
//and I want to insert new information
y.name ="Bon";
y.age =12;
y.subject.push_back("history");
y.subject.push_back("physics");
x.push_back(y);
// then I want display all data
cout << "myvector contains:";
for (int i=0; i<x.size(); i++)
{
cout << "Student # " << i+1 <<endl;
cout << " name : " << x.at(i).name <<endl; //Reference in the internet only display a simple vector --
cout << " age : " << x.at(i).age <<endl; //I get stuck to express this and next part
cout <<" Subject : ";
for (int j =0; j < x.at(i).subject.size(); j++)
{
cout << x.at(i).subject.at(j);
}
cout << endl;
cin.get();
return 0;
}