如何从文件读取数据到矢量?

时间:2019-12-09 22:54:34

标签: 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;
            }


};

1 个答案:

答案 0 :(得分:1)

收集评论。请注意,这将最困难的部分(即读写)推入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;
    }
};