简体   繁体   English

使用 Vector 结构,不能向其添加 vector.size

[英]Using Vector structure, can't add a vector.size to it

So basically i have a read() function, to witch i want to read from the file, with student names and their grades, but if im using for(auto i = 0; i < 1000; i++) i have problem with vector size declaration ////所以基本上我有一个 read() 函数,我想从文件中读取学生姓名和成绩,但是如果我使用 for(auto i = 0; i < 1000; i++) 我有向量大小的问题宣言 ////

void read(vector <Student> A, vector<int> ndgrades)
{

   // IF I CHANGE  A.size() to number, I get error, but here A.size() = 0, hwo do i change it.

    for (auto i = 0; i < A.size(); i++) {
        fin >> A[i].name;
        fin >> A[i].srname;
        int j = 0;
        double vid = 0;
        int grade;
        while (true)
        {
            fin >> grade;
            if (grade == 0) {
                cout << "bad grade" << endl;
                cout << "end of the program" << endl;

            }
            else if (j == 14)break;
            else {
                ndgrades.push_back(grade);
                vid += grade;
                j++;
            }
        }
        double average = vid / j * 1.0;
      //  cout << "Enter egzam result" << endl;
        fin >> A[i].egz;
        A[i].last = average * 0.4 + A[i].egz * 0.6;
        A[i].mediana = (average + A[i].egz) / 2;

        ndgrades.erase(ndgrades.begin(), ndgrades.begin() );
    }

}

There are a number of issues with this code.这段代码有很多问题。 First of all, you're passing in the vectors A and ndgrades by value, so after the read function completes, the caller will not get the results back as expected.首先,您按值传递向量Andgrades ,因此在read函数完成后,调用者将无法按预期返回结果。 You should pass by reference so your function can modify the original instances in the caller, as shown below with the & in the type.您应该通过引用传递,以便您的函数可以修改调用者中的原始实例,如下所示,类型中带有&

void read(vector <Student>& A, vector<int>& ndgrades)
{
    //...

Second, you should just let the vector grow dynamically, rather than try to preallocate or manually resize.其次,您应该让向量动态增长,而不是尝试预先分配或手动调整大小。 To do this, create a Student instance then add it to the list thus:为此,请创建一个Student实例,然后将其添加到列表中:

    while (true) {
        Student s;
        fin >> s.name;
        fin >> s.srname;
        A.push_back(s);

In the last part, it's not clear what some of the code is trying to achieve.在最后一部分中,尚不清楚某些代码试图实现什么。 If you want to keep a list of grades for each student, why not have a vector within the Student type itself?如果您想保留每个学生的成绩列表,为什么不在 Student 类型本身中有一个向量?

Also the declaration of fin is not shown, but assuming it is the input file, you can terminate your loop with:也没有显示fin的声明,但假设它是输入文件,您可以使用以下命令终止循环:

        if (!fin.good())
            break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM