C 中向量上的非传统局部变量误差

Uninitialized local variable error on a vector in C++

本文关键字:非传统 局部变量 误差 向量      更新时间:2023-10-16

我正在尝试完成我的C 类的作业,并且我遇到了一个问题,我无法找到迄今为止的答案。

我要做的是创建一个可以无限期增长的向量,直到用户打破循环为止。该矢量必须容纳班级对象以保存学生名称和成绩信息。我有班级工作;该程序目前似乎给我麻烦的唯一部分是向量。

我继续获得此错误代码:

错误c4700:使用的本地变量"学生"使用了

这是我的功能:

void vectorfctn(){
   vector<student> *students; //I'm assuming this is what is causing the error
   string stud;
   double ex1;
   double ex2;
   double hw;
   double fex;
   char exit;
   do {
    cout << "Enter Student Name" << endl; cin >> stud;
    cout << endl << "Enter First Exam" << endl; cin >> ex1;
    cout << endl << "Enter Second Exam" << endl; cin >> ex2;
    cout << endl << "Enter Homework" << endl; cin >> hw;
    cout << endl << "Enter Final" << endl; cin >> fex;
    student* s1 = new student(stud, ex1, ex2, hw, fex);
    s1->calcFinalGrade();
    students->push_back(*s1); //This is the line referenced by visual studio in the error
    cout << "Would you like to continue? y or n" << endl;
    cin >> exit;
    delete s1;
   } while (exit != 'n');
for (size_t i = 0; i < students->size(); i++) {
    cout << students->at(i).calcFinalGrade() << endl;
}
};

我将如何初始化矢量而不限制其大小?我用矢量吸吮,并且并不真正了解它们,因此任何建议都将不胜感激。

students向量不需要指针。
替换 vector<student> *students;vector<student> students;

students->pushback() to students.pushback()

首先,声明 vector 对象,而不是指针。

vector<student> students;

第二,声明student 本地,而不是指针和new

student s1(stud, ex1, ex2, hw, fex);

第三,push_back

students.push_back(s1);

vector *students;创建vector的指针,而不是向量本身。当您尝试通过 ->调用其成员函数时,尚未创建向量,因此您无法将任何内容推入内部的任何内容,因此无法将其推送。

要解决此问题,只需在vector *students;上删除 *,然后用students.push_back

替换所有students->push_back

您正在创建指向向量(声明)的指针,但实际上并未创建向量(定义)。正如其他人所说,只需在堆栈上创建向量即可。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
void vectorfctn() {
    vector<Student> students;
    string stud;
    double ex1;
    double ex2;
    double hw;
    double fex;
    char exit;
    do {  // todo: validate user input
        cout << "Enter Student Name" << endl;        getline(cin, stud);
        cout << endl << "Enter First Exam" << endl;  cin >> ex1;
        cout << endl << "Enter Second Exam" << endl; cin >> ex2;
        cout << endl << "Enter Homework" << endl;    cin >> hw;
        cout << endl << "Enter Final" << endl;       cin >> fex;
        //Student s1 = Student(stud, ex1, ex2, hw, fex);
        //s1.calcFinalGrade();  // does this really need to be here?  It's also used below in the for loop
        //students.push_back(s1);
        students.push_back(Student(stud, ex1, ex2, hw, fex));
        cout << "Would you like to continue? y or n" << endl; cin >> exit;
    } while (exit != 'n');
    for (auto student : students) { cout << student.calcFinalGrade() << endl; }
};

使用push_back将您想要的任何内容附加到向量。

vector<int> myVec;
myVec.push_back(2);
myVec.push_back(3);

我认为您的push_back语法不正确。这有帮助吗?