我是c++初学者 现在我被困在一个练习中,我不知道如何解决它
练习的目标是:编写一个程序,要求用户输入 10 个不同的人早餐吃的薄煎饼的数量,并从大到小列出一个列表,例如: 第 6 个人吃了:10 个煎饼 第 1 个人吃了:6 个煎饼 等等……
我有这个代码:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int person_num = 0;
int pancakes;
vector<int> pancake_list;
while (true) {
person_num = person_num + 1;
cout << "Please enter the number of pancakes eaten by Person #" << person_num << " ";
cin >> pancakes;
pancake_list.push_back(pancakes);
sort(begin(pancake_list), end(pancake_list));
reverse(begin(pancake_list), end(pancake_list));
if (person_num == 10) {
system("cls");
for (int i = 0; i < pancake_list.size(); i++) {
cout << pancake_list[i] << endl;
}
system("pause");
}
}
return 0;
}
问题是我不知道如何将排序和反转的煎饼分配给合适的人 请帮忙解释一下
对不起我的英语
最佳答案
我会用 c++ map 做点什么.如果您知道自己想要对事物进行排序,则可以使用 map 键排序让您的生活更轻松一些。在这种情况下,使用吃掉的煎饼数量作为 map 中的键,并将人数作为值 - 这样列表已经排序,您可以向后迭代以反向排序顺序打印它。像这样:
#include "stdafx.h"
#include <iostream>
#include <map>
using namespace std;
int main()
{
int person_num = 0;
int pancakes;
multimap<int, int> pancake_map;// Use multimap incase two people ate the same number of pancakes. Note: there are no guarantees about the relative order of elements with the same key.
while (true) {
person_num = person_num + 1;
cout << "Please enter the number of pancakes eaten by Person #" << person_num << " ";
cin >> pancakes;
pancake_map.insert(make_pair(pancakes,person_num));// c++ multimap stores things sorted by key value, so we don't have to do any sorting
if (person_num == 10)
{
system("cls");
// to print the ascending sorted list, iterate through the container forwards
for (multimap<int,int>::iterator it=pancake_map.begin(); it != pancake_map.end(); ++it)
{
cout << "Person number " << it->second << " ate " << it->first << " pancakes." << endl;
}
cout << endl;// little bit of formatting...
// to print the reverse sorted list, iterate backwards
for (multimap<int,int>::reverse_iterator it=pancake_map.rbegin(); it != pancake_map.rend(); ++it)
{
cout << "Person number " << it->second << " ate " << it->first << " pancakes." << endl;
}
system("pause");
break; // I added this to escape the loop after entering 10 people, remove it if you want.
}
}
return 0;
}
关于C++练习煎饼,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29369451/