C ++中向量上未初始化的局部变量错误

时间:2017-11-24 03:49:50

标签: c++ vector

我正在尝试为我的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;
}
};

如何在不限制其大小的情况下初始化矢量?我厌倦了矢量,并没有真正理解它们,所以任何建议都会非常感激。

5 个答案:

答案 0 :(得分:3)

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

。{

students->pushback()students.pushback()

答案 1 :(得分:1)

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

vector<student> students;

其次,在本地声明student ,而不是指针和new

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

第三,push_back

students.push_back(s1);

答案 2 :(得分:1)

vector *students;创建一个vector的指针,而不是向量本身。当您尝试通过 - &gt;调用其成员函数时,尚未创建任何向量,因此您无法在内部推送任何内容,从而导致错误。

要解决此问题,只需在vector *students;删除*并将所有students->push_back替换为students.push_back

答案 3 :(得分:0)

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

#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; }
};

答案 4 :(得分:-1)

使用push_back将任何你想要的东西附加到矢量。

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

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