【发布时间】:2015-05-10 16:44:37
【问题描述】:
我正在尝试编写煎饼吃者的 C++ 代码。我输入了 7 个人吃的煎饼的数量。我找到了最大值。和分钟。食客,但我无法按人们吃的煎饼数量对它们进行分类。有人可以帮我吗?
谢谢。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
struct Person
{
string name;
unsigned int pancakesAte;
};
int main()
{
const int NUM_PEOPLE = 7;
vector<Person> people;
unsigned int mostPancakesIndex = 0;
unsigned int leastPancakesIndex = 0;
for(int index = 0; index < NUM_PEOPLE; index++)
{
std::stringstream ss;
Person person;
ss << "Person " << index;
person.name = ss.str();
cout << "how many did person " << person.name << " eat? ";
cin >> person.pancakesAte;
people.push_back(person);
if ( person.pancakesAte > people[mostPancakesIndex].pancakesAte ){
mostPancakesIndex = index; }
if ( person.pancakesAte < people[leastPancakesIndex].pancakesAte ){
leastPancakesIndex = index; }
}
std::vector<Person>::iterator iter = people.begin();
while (iter != people.end())
{
cout << iter->name << " ate " << iter->pancakesAte << " pancakes." << endl;
++iter;
}
cout << people[mostPancakesIndex].name << " ate the most pancakes - he/she ate " << people[mostPancakesIndex].pancakesAte << " pancakes." << endl;
cout << people[leastPancakesIndex].name << " ate the least pancakes - he/she ate " << people[leastPancakesIndex].pancakesAte << " pancakes." << endl;
}**strong text**
强文本
【问题讨论】:
-
你不需要排序,std::minmax_element 应该做你需要的。
-
İ如果您运行代码,它会打印每个人吃了多少煎饼,但是当我打印它们时,我想按煎饼编号对它们进行排序,然后再次打印。