c++ - 如何从文件读取数据到向量?
问题描述
所以我有这段代码,其中 Group 类的对象具有来自 Student 类的对象的向量。我已经将有关学生的信息从向量写入文件,但我无法读取这些信息。我怎样才能做到这一点?
到目前为止,这是我的代码:
class Group
{
private:
string name;
vector <Student*> studentList;
public:
~Group();
Group(void);
Group(string s);
void addStudent(string name,int age,int stNum);
void removeStudent(int stNum);
friend ostream& operator << (std::ostream& out, const Group& g) {
out << g.name << "\n";
out << g.studentList.size() << "\n";
for (unsigned i=0;i<g.studentList.size();i++) {
out<< g.studentList[i]->getStudentName()<<"\n";
out<< g.studentList[i]->getStudentAge()<<"\n";
out<< g.studentList[i]->getStudentNumber()<<"\n"<<endl;
}
return out;
}
friend istream& operator>>(std::istream& in, Group& g){
in >> g.name;
for (unsigned i=0;i<g.studentList.size();i++) {
//READ DATA FROM FILE
}
return in;
}
};
解决方案
收集评论。请注意,这会将困难的部分,即阅读和写作推入Student
,而我将其留空。通常我会这样做,因为我很邪恶,但显然在这种情况下它已经写好了。
主要变化:
- 没有
Student
指针。减少内存管理开销和更好的缓存友好性!由格拉布萨的锤子。多么节省。 Student
做Student
阅读和写作。std::vector
处理元素计数,因此不需要将其存储在输出中并从输出中读取。注意:这可能会稍微减慢读取速度,因为您无法在vector
.
#include <string>
#include <iostream>
#include <vector>
// note the lack of using namespace std;
// it can be problematic, and especially so in a header.
class Student
{
//fill in the blanks
friend std::ostream& operator <<(std::ostream& out, const Student& s)
{
//fill in the blanks
return out;
}
friend std::istream& operator >>(std::istream& in, const Student& s)
{
//fill in the blanks
return in;
}
};
class Group
{
private:
std::string name;
std::vector<Student> studentList; // death to pointers!
public:
//~Group(); // Don't need a destructor without the pointer
Group(void);
Group(std::string s);
void addStudent(std::string name, int age, int stNum);
void removeStudent(int stNum);
friend std::ostream& operator <<(std::ostream& out, const Group& g)
{
out << g.name << "\n";
//out << g.studentList.size() << "\n"; not necessary. vector handles it.
for (std::vector<Student>::const_iterator it = g.studentList.cbegin();
it != g.studentList.cend();
++it)
{
if (!(out << *it))// let Student's << do all the work
{ // write failed. Might as well stop trying to write.
break;
}
}
return out;
}
friend std::istream& operator>>(std::istream& in, Group& g)
{
in >> g.name;
Student temp;
while (in >> temp) // let Student's >> do all the work
{
g.studentList.push_back(temp);
}
return in;
}
};
推荐阅读
- python - 为什么使用 NonlinearBlockGS 求解器在耦合组中第一个组件的输出不直接传递到第二个组件的输入?
- go - 去审查 Sprintf 上的警告
- sql - 使用define来存储select语句的结果
- jquery - jQuery - 移动设备上的特定指令
- node.js - AWS lambda 中的 Google 驱动 API
- angularjs - 如何在我的 angularjs 服务的 jasmine 中覆盖 this.service
- javascript - 如何从 XML 创建注入 React 组件
- c++ - 如何将 ampl 中的集合表示为 C++ 中的向量?
- python - 在 Python 中定义范围命令的条件
- scala - Scala中带有问号的URL模式匹配