如何按C 中的向量对升序和下降顺序进行排序

How to sort ascending and descending order by vectors in C++

本文关键字:顺序 排序 升序 何按 向量      更新时间:2023-10-16

我正在尝试编写煎饼的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::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.