gpt4 book ai didi

c++ - 打印 vector 的结构元素

转载 作者:搜寻专家 更新时间:2023-10-31 01:51:18 47 4
gpt4 key购买 nike

我正在学习 vector 。我尝试实现一个代码来打印一个 vector 的结构元素,如下所示。互联网上的许多资源只教我一个简单的 vector 。何时打印它,我感到很困惑。但是,尽管更改是根本性的(在结构或循环中),但任何改进代码质量和优雅的建议都是开放的。

非常感谢。

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

最佳答案

在这里,添加了一些评论和内容。不确定这是否是您要找的东西,但它就在这里。

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string> // string would be welcome here!

struct _student // the typedef thing is not necessary in C++
{
std::string name; // i find this "using namespace ..." thing a bad habit, it can make code harder to read
int age;
std::vector<std::string> subject;
};

int _tmain(int argc, _TCHAR* argv[])
{
std::vector<student> x;
student y;
size_t size; // calling vector.size() every iterations is a bad idea, performance-wise
size_t size_subj; // same

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);

y.name = "Bon";
y.age = 12;
y.subject.clear(); // clear subjects of the other student
y.subject.push_back("history");
y.subject.push_back("physics");
x.push_back(y);

std::cout << "my vector contains:";
for (int i = 0, size = x.size(); i < size; ++i)
{
size_subj = x[i].subject.size();
// I prefer using operator[] when I'm sure nothing can go wrong
std::cout << "Student # " << i + 1 <<endl;
std::cout << "\tname: " << x[i].name <<endl;
std::cout << "\tage: " << x[i].age <<endl;
std::cout << "\tSubjects: ";
for (int j = 0; j < size_subj; ++j)
std::cout << x[i].subject[j];
std::cout << endl;
}
return 0;
}

最后,使用 std::vector< std::string* > 或 std::vector< std::string& > 在性能方面可能是一个更好的主意,具体取决于您以后打算用它做什么。

关于c++ - 打印 vector 的结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13983085/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com