c++ - C++读取访问冲突,结构 vector

标签 c++ exception vector struct error-handling

我有一个“程序”,我想按照自己想的方式行事,但是情况是:

我想创建一个最大元素等于25的结构 vector ,然后通过函数初始化每个结构成员(这次只有名称)。我的问题是我遇到异常错误:( 引发异常:读取访问冲突),我不知道自己做错了什么。 (并且程序需要以一个“-”字符结束输入的名称。)

代码:

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#define MAXstudent 25
#include <sstream> 
#include <vector>
using namespace std;

struct student {
    string name; 
};

void get_input(vector<student>& student_group) {

    for (int i = 0; i < MAXstudent; i++) {

       //name
       string temp_variable = "";
       cout << "Student name: ";
       getline(cin, temp_variable);
       if (temp_variable != "-") {
           //student_group.push_back(student());
           student_group[i].name = temp_variable;
           cout << endl;
       }
       else {
           student_group.push_back(student());
           student_group[i].name = temp_variable;
           break;
       }
   }
}

void show_solution (vector<student>& student_group) {
    int i = 0;
    while (student_group[i].name != "-") {
        cout << "\nSolutions: " << endl;

        cout << endl << i + 1 << '.' << "kert name: " << student_group[i].name;
        i++;
    }

}

int main() {
    srand(time(0));
    vector<student>student_group[MAXstudent];
    get_input(student_group[MAXstudent]);
    show_solution (student_group[MAXstudent]);
}

最佳答案

您的main应该是:

int main() {
    srand(time(0));
    vector<student>student_group(MAXstudent); // create one vector with MAXstudent elements in it
    //vector<student>student_group[MAXstudent]; - this creates MAXstudent vectors with 0 elements in each
    get_input(student_group);
    show_solution (student_group);
}

在您的代码中,您创建了 vector 数组,并使用了超出该数组范围的 vector 。您应该了解自己在做什么,而不是创建随机代码并期望它能以某种方式工作。

关于c++ - C++读取访问冲突,结构 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60119872/

相关文章:

c++ - 在 Visual Studio 4.0 中使用标准模板库

c++ - 在 C++ 中将 typedef 区分为相同类型

c++ - cppcheck 如何抑制内联不匹配抑制?

html - 使用矢量图标图像中的图标

c++ - 从 vector 中删除重复项,递归 C++

C++ 类型转换数组

exception - Composer init(新项目)因 Symfony RuntimeException 中止

java - 如果一个方法必须只调用一次而再次调用该方法,则抛出哪个异常?

java - 尝试编译简单的 java 程序时出现 NumberFormatException

c# - 以任意角度从墙上弹回球?