C ++打印数组列表按顺序?

时间:2014-07-15 12:45:53

标签: c++ arrays c++11

我已经被分配了一个关于c ++的任务,我差不多完成了它,但是我被困在最后 “奖金”任务,即:

修改程序,使其按照所有10个人吃的煎饼数量顺序输出一个列表。 即 人4:吃了10个煎饼

第3个人:吃了7个煎饼

人8:吃4个煎饼

...

第5个人:吃了0个煎饼

注意这个人的号码应该与他吃的煎饼数量正确匹配!

到目前为止我得到的代码:

#include <iostream>

using namespace std;

int main()
{
int temp=0;
int temp2=0;
int minimum,location=1;
int pan[10] = {};
for(int i=0;i<11;i++)
{
    cout << "How many pancakes did person " << i << " eat? ";
    cin >> pan[i];
}
for(int i=0;i<11;i++)
{
    if(pan[i]>temp)
    {
        temp=pan[i];
        temp2=i;
    }
}
minimum = pan[0];
for(int i=1;i<11;i++)
{
    if(pan[i] < minimum)
    {
        minimum = pan[i];
        location=i;
    }
}
cout << "The person who ate the most pancakes is person " << temp2 << endl;
cout << "The person who ate the least pancakes is person " << location << endl;
return 0;


}

那么,如何根据吃的煎饼数量和人数来打印正确的订单?提前谢谢!

编辑:我只允许使用:

变量,数据类型和数值运算符

基本输入/输出

逻辑(if语句,switch语句)

循环(for,while,do-while)

阵列

3 个答案:

答案 0 :(得分:1)

您可以使用std::map将人物作为键,将煎饼数量作为数据,并使用自定义比较器功能来比较煎饼的数量。

然后按顺序打印就像从开始到结束迭代一样简单。

答案 1 :(得分:0)

你需要阅读关于排序算法,阅读任务的限制让我相信这是奖金的目标。排序算法越简单:

1 - http://en.wikipedia.org/wiki/Bubble_sort
2 - http://en.wikipedia.org/wiki/Insertion_sort

阅读代码,你正在计算煎饼食用人的最小和最大值。在实现排序时,这两个可以很容易地作为数组中的第一个和最后一个人

找到

我建议保存人员索引和煎饼吃数(例如:使用std :: pair)如果不允许使用对(可以自己制作和结构)

struct pair { long first; long second; };

这是在通过煎饼食用计数对数组进行排序时维护人员索引信息所必需的。

一些示例代码:

std::vector<std::pair<long, long>> pan(10);

for(int i=0;i<11;i++)
{
    cout << "How many pancakes did person " << i << " eat? ";
    cin >> pan[i].second;
    pan[i].first = i;
}

// sort using bubble or insertion sort

cout << "The person who ate the most pancakes is person " << pan.back().first << endl;
cout << "The person who ate the least pancakes is person " << pan.front().first << endl;

// Print persons in order.

答案 2 :(得分:0)

首先,你的for循环无效。

`for(int i = 0; i&lt; 11; i ++)

你的桌子大小是10(有效索引:0,1,2,3,4,5,6,7,8,9没有10!)`

可以使用例如vector和一些stl函数替换这些所有循环:

vector<int> personsPancakes = {3, 7, 2, 8, 4};

auto maxIt = max_element(begin(personsPancakes), end(personsPancakes)); // iterator to max element
auto minIt = min_element(begin(personsPancakes), end(personsPancakes)); // iterator to min element

cout << "Max value index: " << distance(begin(personsPancakes), maxIt) << " Value: " << *maxIt << endl;
cout << "Min value index: " << distance(begin(personsPancakes), minIt) << " Value: " << *minIt << endl;

输出:

Max value index: 3 Value: 8
Min value index: 2 Value: 2
相关问题