如何将for循环转换为for-each循环?

时间:2020-07-31 18:06:20

标签: c++ arrays

我的任务是将for循环转换为for-each循环。

任务从创建二维数组6x30开始。这代表了6个班级,每个班级30名学生。数组中的每个位置都包含一个介于55和100之间的随机数,代表学生的分数。

接下来,我将该阵列显示到控制台上。

接下来,我计算每个班级的平均分数。

接下来,我在6个班级中找到最高的平均值,并将其显示在屏幕上。

我在MacBook Pro上使用Xcode。

问题:如何将for循环正确转换为for-each循环?

我的代码如下:

#include <iostream>
#include <iomanip>

using namespace std;

const int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;

void bubbleSort(int arr[], int n){
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] < arr[j + 1])
                swap(arr[j], arr[j + 1]);
        }
    }
}

void classGradeGeneration() {
    int arrayOne[NUM_CLASSES][NUM_STUDENTS_PER_CLASS], classAverage[NUM_CLASSES];
    //Generating random average student scores until array filled
    for (int classNumber = 0; classNumber < NUM_CLASSES; classNumber++) {
        for (int column = 0; column < NUM_STUDENTS_PER_CLASS; column++) {
            arrayOne[classNumber][column] = rand() % 46 + 55;
        }
    }
    //Displaying array of student scores
    for (int classNumber = 0; classNumber < NUM_CLASSES; classNumber++) {
        cout << "Class " << classNumber + 1 << ": ";
        for (int column = 0; column < NUM_STUDENTS_PER_CLASS; column++) {
            cout << setw(3) << arrayOne[classNumber][column] << " ";
            classAverage[classNumber] += arrayOne[classNumber][column];
        }
        cout << endl;
    }
    cout << endl;
    int averageScore, averageOfClasses[NUM_CLASSES];
    //Displaying average class scores
    for (int temp = 0; temp < NUM_CLASSES; temp++) {
        averageScore = classAverage[temp] / NUM_STUDENTS_PER_CLASS;
        cout << "Class " << temp + 1 <<" Average score: " << averageScore << endl;
        averageOfClasses[temp] = averageScore;
    }
    cout << endl;
    bubbleSort(averageOfClasses, NUM_CLASSES); // Sorting average scores highest to lowest

    cout << endl;
    cout << "The highest average score is: " << averageOfClasses[0];
    cout << endl;    
}

int main () {
    srand(time(NULL));
    classGradeGeneration();
    cout << endl << endl;
}

以下是示例输出:

Sample Output

1 个答案:

答案 0 :(得分:3)

自C ++ 11起,您可以将range-based forstd::array一起使用

constexpr int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;
std::array<std::array<int, NUM_STUDENTS_PER_CLASS>, NUM_CLASSES> arr;
for (/*const*/ auto& ln : arr) {
    std::cout << "LINE" << std::endl;
    for (/*const*/ auto& elem : ln) {
        std::cout << "elem" << std::endl;
    }
}

或for_each(如果需要)

std::for_each(arr.begin(), arr.end(), [](/*const*/ auto& line) {
    std::cout << "LINE" << std::endl;
    std::for_each(line.begin(), line.end(), [](/*const*/ auto& elem) {
        std::cout << "elem" << std::endl;
        });
    });

但在这种情况下,我更倾向于基于范围。

如果使用c样式数组,则for_each参数将是指针,而不是迭代器。

int arr[NUM_CLASSES][NUM_STUDENTS_PER_CLASS], classAverage[NUM_CLASSES];
std::for_each(std::begin(arr), std::end(arr), [](/*const*/ auto& line) {
    std::cout << "LINE" << std::endl;
    std::for_each(std::begin(line), std::end(line), [](/*const*/ auto& elem) {
        std::cout << "elem" << std::endl;
        });
    });

所以您的代码可能看起来像这样

constexpr int NUM_CLASSES = 6, NUM_STUDENTS_PER_CLASS = 30;
std::array<std::array<int, NUM_STUDENTS_PER_CLASS>, NUM_CLASSES> arr;

// set random values
for (auto& ln : arr) {
    for (auto& elem : ln) {
        elem = std::rand() % 100;
    }
}

// calculate
float avgScore = 0.0F;
for (const auto& ln : arr) {
    const auto avgGroupScore = std::accumulate(std::begin(ln), std::end(ln), 0.0F) / (std::end(ln) - std::begin(ln));
    avgScore = std::max(avgScore, avgGroupScore);
    std::cout << "avg group score=" << avgGroupScore << "; current avgScore=" << avgScore << std::endl;
}