【发布时间】:2018-05-05 19:40:12
【问题描述】:
我正在尝试制作一个用户输入学生姓名和考试成绩的程序。该程序将返回在曲线上评分的分数以及应获得该分数的学生的姓名。我遇到的问题是配对数组仅在下面输出 -858993460 是我的代码,感谢您的帮助。谢谢。
int main()
{
const int MAX = 300;
int n;
int y;
int x; // find what the difference between the highest score and 100
std::vector<std::pair < std::string, int>> vect;
//Asks for # of tests for loop
std::cout << "Hello, How many tests do you need to grade?" << std::endl;
std::cin >> n;
std::cout << "Please enter a grade then press enter. Repeat until you have
reached the number specified in the previous step" << std::endl;
std::cout << "DO NOT ENTER DECIMALS" << std::endl;
// declare array
std::string name[MAX];
int score[MAX];
//pairs arrays
for (int i = 0; i < MAX; i++)
{
vect.push_back(make_pair(name[i], score[i]));
}
// gets input for names and test scores
for (int i = 0; i < n; i++)
{
std::cin >> name[i] >> score[i];
}
// sorts tests
std::sort(vect.begin(), vect.end());
//add a space for easier reading
std::cout << " " << std::endl;
//finds the difference between the highest scores and 0
x = 100 - vect[0].second;
for (int i = 0; i < n; i++)
{
std::cout << vect[i].first << vect[i].second + x << std::endl;
}
std::cout << "enter a value then press enter to close";
std::cin >> y;
return 0;
}
【问题讨论】:
-
您将未初始化的分数值推送到
vect。当您使用cin读取实际值时,它只会更新score[i],而不是vect中的对。 -
您拿两本书,复制每本书的每一页,然后将这两页合并成第三本书,其中包含前两本书的每一页。只有在您创建了第三本书之后,您才能返回并在第一本书的其中一页上乱涂乱画。你希望在第三本书中看到你乱写的东西吗?用你的数组替换前两本书,用你的向量对替换第三本书,你应该能够自己找出哪里出错了。
-
A
std::vector存储副本。在您的第二个循环中,names[i]和scores[i]不会神奇地更改您在前一个循环中放置在向量中的pair项。