'How can I sort two arrays in descending order?

I am trying to write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10).

I need to modify the program so that it outputs a list in order of number of pancakes eaten of all 10 people.

Example:

Person 4: ate 10 pancakes
Person 3: ate 7 pancakes
Person 8: ate 4 pancakes
...
Person 5: ate 0 pancakes

I have been able to sort the number of pancakes into descending order, however I am struggling to assign the correct Person to their number of pancakes.

Here is my code so far:

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;
}

Any help would be greatly appreciated!



Solution 1:[1]

You can take advantage of the sorting of the 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;
}

Solution 2:[2]

Use indirection. Set up an array of indices 0 to n and sort that index array by defering the comparison to the count array:

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;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 liu chao
Solution 2 j6t