如何在 C++ 中连接两个数组并仅对其中一个进行排序?

问题描述 投票:0回答:1

我是 C++ 新手,正在用煎饼做 Buzzy 的练习。但我完全不知道如何解决它的最后一部分:

修改程序,使其按照 10 个人吃过的煎饼数量的顺序输出一个列表。

第四个人:吃了10个煎饼
第三个人:吃了7个煎饼
第8个人:吃了4个煎饼
...
第5个人:吃了0个煎饼

这就是我目前拥有的。

#include <iostream>
using namespace std;

int main() {

int cc[10]; //the array for pancakes eaten.
int pn[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //"number of the person" array.

cout << "how many pancakes they ate?\n\n";

for (int i = 0, n = 0; i < 10 && n < 10 ; i++, n++){
 cout << "Person " << pn[n] << ": ";
 cin >> cc[i];
}

cout << "\n";

for (int i = 0, n = 0; i < 10 && n < 10 ; i++, n++){

  cout << "person number " << pn[n] << " ate " << cc[i] << " pancakes\n";
}

return 0;
}

但老实说,我不知道我的想法是否正确。此时非常困惑。

c++ arrays sorting
1个回答
0
投票

一个简单的解决方案是不使用两个单独的数组来存储人数和他们吃的煎饼的数量。创建一个

struct
,其中包含关于 one 人的信息以及该人吃了的煎饼数量:

struct person {
    int number;
    int pancakes;
};

然后你只需要一个数组:

person persons[10];  // or  std::array<person, 10> persons;
for (size_t i = 0; i < std::size(persons); ++i) persons[i].number = i + 1;

输入可以使用基于范围的

for
循环:

for (auto& p : persons) {
    std::cout << "Person " << p.number << ": ";
    std::cin >> p.pancakes;
}

同理,输出:

for (auto& p : persons) {
    std::cout << "person number " << p.number << " ate " << p.pancakes
              << " pancakes\n";
}

现在,缺少的是在上面的结果打印之前应该完成的实际排序。我建议将

std::sort
与用户定义的比较函子一起使用,例如 lambda:

// lambda function:
auto comp = [](person& lhs, person& rhs) {
    return lhs.pancakes > rhs.pancakes;
};

// using std::sort with the lambda:
std::sort(std::begin(persons), std::end(persons), comp);
© www.soinside.com 2019 - 2024. All rights reserved.