使用Vector结构时的vector.size问题及学生数据读取的vector大小异常
Let’s break down your problems and fix them step by step—most of the issues come from how you’re handling vector parameters and structuring your file-reading loop:
1. You’re Passing Vectors by Value (Not Reference)
Right now, your read function takes vector<Student> A and vector<int> ndgrades as value parameters. That means the function works on copies of your original vectors, not the actual vectors you created outside. So any changes you make to A inside the function won’t affect the original vector—and since the copy starts empty, A.size() is 0, so your loop never runs at all.
Fix this by passing them as references (add & to the parameter types):
void read(vector<Student>& A, vector<int>& ndgrades) { // Rest of your code goes here }
2. Your Loop Relies on an Empty Vector’s Size (Wrong Approach)
You don’t need to predefine the size of A before reading from the file. Instead, read data until there’s no more left, and build the vector as you go. The original for loop using A.size() is useless here because A starts empty—you can’t access A[i] if the vector has no elements.
Here’s the restructured loop that fixes this:
void read(vector<Student>& A, vector<int>& ndgrades) { Student tempStudent; // Temporary object to hold each student's data // Keep reading until we run out of student names while (fin >> tempStudent.name >> tempStudent.srname) { int j = 0; double vid = 0; int grade; ndgrades.clear(); // Empty the grades vector for the new student while (true) { fin >> grade; if (grade == 0) { cout << "bad grade" << endl; cout << "end of the program" << endl; return; // Exit early on invalid grade } else if (j == 14) { break; // Stop after 14 grades } else { ndgrades.push_back(grade); vid += grade; j++; } } double average = vid / j * 1.0; fin >> tempStudent.egz; tempStudent.last = average * 0.4 + tempStudent.egz * 0.6; tempStudent.mediana = (average + tempStudent.egz) / 2; A.push_back(tempStudent); // Add the completed student to the vector } }
3. Fixing the ndgrades Erase Mistake
Your original line ndgrades.erase(ndgrades.begin(), ndgrades.begin() ); does nothing—it erases a range from the start to the start (zero elements). Use ndgrades.clear(); instead to properly empty the vector for each new student.
4. Why You Couldn’t Add vector.size() Values
When you tried to use A.size() as an index (like A[A.size()]), that’s invalid because vector indices only go from 0 to size()-1. Instead of trying to assign to A[i] when the vector is empty, create a temporary Student object, fill it with data, then use push_back to add it to A—this handles the vector’s size automatically.
Key Takeaways
- Always pass vectors by reference if you need to modify them in a function.
- Don’t rely on pre-existing vector size for file reading—build the vector as you read data.
- Use
push_backto add elements to empty vectors instead of trying to assign to indices.
内容的提问来源于stack exchange,提问作者ugnius kolo

