我的代码在第20行崩溃,我尝试按用户输入的名称初始化名称。似乎矢量超出了范围。请帮我弄清楚背后的问题和原因。 此代码从用户输入学生数据,根据成绩对其进行排序,然后将其打印回来。 这是代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct studentDatabase{
std::string name;
int grade;
};
void getUserInput(std::vector<struct studentDatabase> &student)
{
std::cout << "No of students for which the data is to be entered n";
int noOfStudents(0);
std::cin >> noOfStudents;
for (unsigned int i = 0; i < noOfStudents; ++i)
{
std::cout << "Enter name n";
std::cin >> student.at(i).name; // this is where it is crashing
//not sure why
std::cout << "Enter grade n";
std::cin >> student.at(i).grade;
}
}
void sort(std::vector<struct studentDatabase> &student)
{
for (unsigned int i = 0; i < student.size(); ++i)
{
for (unsigned int j = 0; j < student.size() -i; j++)
{
if (student.at(i).grade < student.at(j).grade)
std::swap(student.at(i), student.at(j));
}
}
}
void printStudentOrder(const std::vector<struct studentDatabase> &student)
{
for (unsigned int i = 0; i < student.size(); ++i)
std::cout << student.at(i).name << " got a grade of " <<
student.at(i).grade << std::endl;
}
int main()
{
std::vector<struct studentDatabase> student;
getUserInput(student);
sort(student);
printStudentOrder(student);
return 0;
}
答案 0 :(得分:1)
std::vector<studentDatabase>
最初是一个空容器。因此,当您通过vector
访问vector::at(i)
时,找不到任何项目,并且会引发out_of_range
异常。
您可以先将数据收集到本地studentDatabase
变量中,然后将其放入向量中,例如:
for (unsigned int i = 0; i < noOfStudents; ++i)
{
studentDatabase s;
std::cout << "Enter name n";
std::cin >> s.name;
std::cout << "Enter grade n";
std::cin >> s.grade;
student.push_back(s);
}
答案 1 :(得分:1)
最初你的矢量是一个空容器。因此,当您尝试访问该向量时,它将引发异常。
void getUserInput(std::vector<struct studentDatabase> &student)
{
std::cout << "No of students for which the data is to be entered n";
int noOfStudents(0);
std::cin >> noOfStudents;
for (unsigned int i = 0; i < noOfStudents; ++i)
{
studentDatabase stud;
std::cout << "Enter name n";
std::cin >> student.name; // this will get student name.
std::cout << "Enter grade n";
std::cin >> student.grade; // this will get student grade.
student.push_back(stud); // Here we are storing the data into vector.
}
}
您需要将数据存储到vecotor中以访问它们以避免异常。 将此代码段替换为您的代码,您的问题将得到解决。
答案 2 :(得分:0)
此时,您正在尝试访问位置i
中的元素,但该向量最初为空。 vector
构造的行为不像旧式数组,您必须在其中指定大小,并且所有这些空格都保留在内存中。
您必须创建您的矢量,其大小如此
std::vector<struct studentDatabase> student(30);
getUserInput(student);
但如果您之前不知道尺寸,我建议您逐个获取输入并使用push_back()