gpt4 book ai didi

c++ - "Process terminated with status -1073741819"带 vector 的简单程序

转载 作者:行者123 更新时间:2023-11-28 00:17:20 25 4
gpt4 key购买 nike

出于某种原因,每当我运行我的程序时,我都会收到“进程终止状态 -1073741819”错误,我读到有些人因为代码块/编译器出现问题而收到此错误,我只是想在我重新安装编译器等之前知道我的代码是否有问题。我正在使用 code::blocks 和 GNU GCC 编译器。

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

调度.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

ma​​in.cpp:

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

using namespace std;

int main()
{
Schedule theWeek;
}

最佳答案

这不是编译器错误。

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

您的代码有几处错误,例如,在您的 cpp 中,您声明了一个全局 vector 周,然后它隐藏在构造函数中,因为构造函数将访问 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);
}
}

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

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

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

关于c++ - "Process terminated with status -1073741819"带 vector 的简单程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29408496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com