我正在嘗試撰寫一個程式,要求用戶輸入 10 個不同的人(第 1 個人、第 2 個人、...、第 10 個人)早餐吃的煎餅數量。
我需要修改程式,以便它按所有 10 人吃的煎餅數量的順序輸出一個串列。
例子:
Person 4: ate 10 pancakes
Person 3: ate 7 pancakes
Person 8: ate 4 pancakes
...
Person 5: ate 0 pancakes
我已經能夠將煎餅的數量按降序排序,但是我正在努力為Person他們的煎餅數量分配正確的數量。
到目前為止,這是我的代碼:
int main()
{
int person[10];
int i;
int input;
int n = sizeof(person) / sizeof(person[0]);
// store the number entered by the user in each array element
for(i = 0; i < 10; i)
{
cout << "How many pancakes did Person " << i 1 << " eat? ";
cin >> person[i];
}
cout << endl;
cout << endl;
sort(person, person n, greater<int>()); // sorts array in descending order. "greater()" puts larger numbers first
for(i = 0; i < n; i )
{
cout << "Person " << i 1 << " ate " << person[i] << " pancakes." << endl;
}
return 0;
}
任何幫助將不勝感激!
uj5u.com熱心網友回復:
您可以利用 std::map 的排序。
int main()
{
constexpr int person_num = 10;
multimap<int, int, greater<>> pancakes_person_pairs;
for (int i = 0; i < person_num; i)
{
int cur_person = i 1;
cout << "How many pancakes did Person " << cur_person << " eat? ";
unsigned int cur_pancakes;
cin >> cur_pancakes;
pancakes_person_pairs.insert(make_pair(cur_pancakes, cur_person));
}
cout << endl << endl;
for (const auto& pancakes_person_pair : pancakes_person_pairs)
{
cout << "Person " << pancakes_person_pair.second << " ate " << pancakes_person_pair.first << " pancakes." << endl;
}
return 0;
}
uj5u.com熱心網友回復:
您可以使用std::vectorofstd::pair來存盤 Person 索引及其對應的值。然后,您可以使用比較器函式按值排序。
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<pair<int, int>> person(10);
// store the number entered by the user in each array element
for(int i = 0; i < person.size(); i)
{
person[i].first = i 1;
cout << "How many pancakes did Person " << i 1 << " eat? ";
cin >> person[i].second;
}
cout << endl;
cout << endl;
auto compare = [&](const pair<int, int>& a, const pair<int, int>& b)
{
return a.second > b.second;
};
sort(person.begin(), person.end(), compare);
for(int i = 0; i < person.size(); i )
{
cout << "Person " << person[i].first << " ate " << person[i].second << " pancakes." << endl;
}
return 0;
}
uj5u.com熱心網友回復:
使用間接。設定一個索引陣列 0 到 n 并通過將比較推遲到計數陣列來對該索引陣列進行排序:
vector<int> ind(n);
iota(ind.begin(), ind.end(), 0); // #include <numeric>
sort(ind.begin(), ind.end(),
[&](int a, int b) { return person[a] > person[b]; });
for (int i : ind) {
cout << "Person " << i 1 << " ate " << person[i] << " pancakes." << endl;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429685.html
