如何按C 中的向量对升序和下降顺序进行排序
How to sort ascending and descending order by vectors in C++
我正在尝试编写煎饼的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.
相关文章:
- 在自定义程序中使用本机 Windows 自然顺序排序
- C++ 按数值对元组<字符串、浮点数>然后按字典顺序排序的向量
- 在 C++ 中,以相反顺序排序的最快方法是什么?
- 按字母顺序排序字符数组,然后按长度排序
- 按第一个值的递减顺序对一组对进行排序,然后按第二个值的字母顺序排序
- C 在向量的向量中按字母顺序排序字符串
- 双链表中按字母顺序排序的链接
- 从文件中读取并按字母顺序排序
- 按字母顺序排序阵列C
- 构造函数的初始值设定项列表中的函数调用是否按顺序排序?
- 使用指针数组按字母顺序排序
- 按字母顺序排序,带有 å ä ö
- 按字母顺序排序名称,数组错误
- 如何从对数字进行排序到按C++字母顺序排序
- 从文件C++中按字母顺序排序
- 无法实现从文件按字符串 C++ 中的字母顺序排序的函数
- 并发消息处理按时间顺序排序
- 如何在 std::vector 中查找重复项<strings>并返回一个 std::list 它们按字母顺序排序,在该结果列表中没有重复项
- C++按字母顺序排序字符串
- 按字母顺序排序JSON值