如何用C ++中的向量对升序和降序进行排序

时间:2015-05-10 16:44:37

标签: c++ sorting vector

我正在尝试写一个煎饼吃的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**

强文

1 个答案:

答案 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.