简体   繁体   中英

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 ////

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. 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:

    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?

Also the declaration of fin is not shown, but assuming it is the input file, you can terminate your loop with:

        if (!fin.good())
            break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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