"Process terminated with status -1073741819" 带向量的简单程序

"Process terminated with status -1073741819" simple program with vector

出于某种原因,每当我 运行 我的程序时,我都会收到 "Process terminated with status -1073741819" 错误,我读到有些人因为 code-blocks/the 编译器出现问题而收到此错误,我在我重新安装编译器之类的之前,我只想知道我的代码是否有任何问题。我正在使用 code::blocks 和 GNU GCC 编译器。

我的代码创建了一个向量,该向量存储一周 40 个工作小时,并在该向量内创建一个向量,该向量存储代表这些小时内有空的 5 个人的字母。

Schedule.cpp:

#include <iostream>
#include "Schedule.h"
#include <vector>
#include <string>

using namespace std;

/// Creates a Vector which holds 40 items (each hour in the week)
/// each item has 5 values ( J A P M K or X, will intialize as J A P M K)

vector< vector<string> > week(40, vector<string> (5));

Schedule::Schedule(){
        for (int i = 0; i<40; i++){
            week[i][0] = 'J';
            week[i][1] = 'A';
            week[i][2] = 'P';
            week[i][3] = 'M';
            week[i][4] = 'K';
        }
        // test 
        cout << week[1][3] << endl;
    }

头文件:

#ifndef SCHEDULE_H
#define SCHEDULE_H
#include <vector>
#include <string>

using namespace std;

class Schedule
{
    public:
        Schedule();
    protected:
    private:
        vector< vector<string> > week;

};

#endif // SCHEDULE_H

main.cpp:

#include <iostream>
#include "Schedule.h"
#include <vector>
#include <string>

using namespace std;

int main()
{
    Schedule theWeek;
}

这不是编译器错误。

您的构造函数出现内存错误。

您的代码有几处错误,例如,在您的 cpp 中,您声明了一个全局向量周,然后它隐藏在构造函数中,因为构造函数将访问 Schedule::week .

你的 cpp 应该是这样的:

// comment out the global declaration of a vector week ...
// you want a vector for each object instantiation, not a shared vector between all Schedule objects
// vector< vector<string> > week(40, vector<string> (5)); 


Schedule::Schedule()
{
    for (int i=0;i<40;i++)
    {
        vector<string> stringValues;
        stringValues.push_back("J");
        stringValues.push_back("A");
        stringValues.push_back("P");
        stringValues.push_back("M");
        stringValues.push_back("K");
        week.push_back(stringValues);
    }
}

当您第一次尝试访问您的周向量时,您的代码出现了内存错误:

 week[i][0] = 'J' ;

在您调用该行代码的那一刻,您的 Schedule::week 向量中有 0 个元素(因此 week[i] 已经是一个错误)。