2015-05-10 39 views
-3

我想写一个C++代码的煎饼食者。我输入7人吃的煎饼的数量。我发现了最大值。和分钟。但我不能根据人们吃的煎饼的数量来分类。请任何人帮助我吗?如何在C++中对向量进行升序和降序排列

谢谢。

#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** 

强大的文本

+0

你不需要排序,和std :: minmax_element应该做你所需要的。 – user1937198

+0

如果您运行代码,它会打印每个人吃多少煎饼,但是当我打印它们时,我想按照煎饼数量对它们进行排序,然后重新打印。 –

回答

1

我最后一次使用std::sort,你可以传递一个比较函数来std::sort。因此,如果你想降序排序,你可以传递一个递减的比较函数。如果你想要通过数量不等的煎饼进行分类,你可以编写一个这样的函数。

功能是很容易写:

bool Comparison(const Type& a, const Type& b) 
{ 
    // if you want a to come before b 
    // in the ordering, return true. 
    return // true or false 
} 

排序是通过调用:

std::sort(your_vector.begin(), your_vector.end(), 
      Comparison); // Your ordering function. 
相关问题