2015-05-10 40 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. 
相關問題