【发布时间】:2018-06-29 00:13:49
【问题描述】:
我是非常接触 c++ 的新手,目前正在尝试完成一些小挑战以跟上更简单的方面。
我正在尝试创建一个结构数组(找到的信息表明向量相同且更好)来保存大约 10 人的数据。每个人都有一个“索引”(用于识别 person1、person2、person3 等)、一个“num”(用于存储收集的数据)和一个“rank”(我打算用来对人员进行排序的变量)收集的数据)
代码在编译之前没有显示任何错误,但是,当输入第一条数据时,我收到以下消息:
“调试断言失败!
程序:C:\WINDOWS\SYSTEM32\MSVCP140D.dll 文件:d:\program files\microsoft visual studio\community\vc\tools\msvc\14.12.25827\include\vector 线路:1795
表达式:向量下标超出范围"
我已尝试搜索多个线程,但我似乎无法弄清楚为什么会出现此问题。
我的代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct person
{
int index; /*person number*/
int num; /*number of pancakes eaten*/
int rank; /*rank used for sorting people*/
};
vector<person> people; /*create a vector (array) of "person"'s*/
void getData()
{
cout << "You will be asked to enter data from 10 different people" << endl;
cout << "\n" << "The question is; 'How many pancakes did they eat for breakfast?'" << endl;
cin.get();
for (int i = 1; i <= 10; i++)
{
system("CLS");
int j;
cout << "Person " << i << " : ";
cin >> j;
person temp;
people.push_back(temp);
people[i].index = i;
people[i].num = j;
people[i].rank = i;
}
}
int main()
{
getData(); /*collect data for the people*/
system("CLS");
cout << "Data Collected : " << endl;
system("pause");
}
提前感谢任何可以提供帮助的人。
【问题讨论】: