我是C ++的初学者
现在我被困在运动上,我不知道该怎么解决
练习的目的是:编写一个程序,要求用户输入10个不同的人早餐吃的煎饼的数量,并按从高到低的顺序列出:
六人共吃: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键排序使您的生活更轻松。在这种情况下,将吃掉的煎饼数作为地图中的键,将人员数作为值-这样,该列表已被排序,您可以向后迭代以反向排序的顺序打印它。像这样:
#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++ - C++运动煎饼,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29369451/