首页 > 解决方案 > 如何从文件读取数据到向量?

问题描述

所以我有这段代码,其中 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;
            }


};

标签: c++

解决方案


收集评论。请注意,这会将困难的部分,即阅读和写作推入Student,而我将其留空。通常我会这样做,因为我很邪恶,但显然在这种情况下它已经写好了。

主要变化:

  • 没有Student指针。减少内存管理开销和更好的缓存友好性!由格拉布萨的锤子。多么节省。
  • StudentStudent阅读和写作。
  • 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;
    }
};

推荐阅读