如何在 C++ 中按向量进行升序和降序排序
Posted
技术标签:
【中文标题】如何在 C++ 中按向量进行升序和降序排序【英文标题】:How to sort ascending and descending order by vectors in C++ 【发布时间】: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 应该做你需要的。 İ如果您运行代码,它会打印每个人吃了多少煎饼,但是当我打印它们时,我想按煎饼编号对它们进行排序,然后再次打印。 【参考方案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.
【讨论】:
以上是关于如何在 C++ 中按向量进行升序和降序排序的主要内容,如果未能解决你的问题,请参考以下文章