c++ - 在 C++ 中对列(数组)的平均值进行排序和打印

标签 c++ arrays

我能够从二维数组(列)生成平均值。尽管我无法弄清楚如何对平均值进行排序。我必须创建一个新数组 (rankedscore[])。

任何帮助将不胜感激:

int rankedArtist() // ranked artist based on score
{
    const int A1_SIZE = 5,  A2_ROWSIZE =5, A2_COLSIZE =10;
    string Artist[A1_SIZE]={ "Degas", "Holbien", "Monet", "Matisse", "Valesquez" };
    int Scores[A2_ROWSIZE][A2_COLSIZE] = {{5,5,6,8,4,6,8,8,8,10},{8,8,8,8,8,8,8,8,8,8},
    {10,10,10,10,10,10,10,10,10,10},{5,0,0,0,0,0,0,0,0,0},{5,6,8,10,4,0,0,0,0,0}};

    cout << "\n\n\t-------------------------------------------" << endl;
    cout << "\t\tRanking by Artist"<< endl;
    cout << "\t===========================================" << endl;

    int total = 0;
    float faverage;
    double AverageScore[5];
    double average;
    double rankedscore[A2_ROWSIZE];


    for (int x=0; x<5; x++)
    {
        cout << "\n\t" << Artist[x] << "\t\t";

        for (int col = 0; col < A2_COLSIZE; col++)
        {
            total+=Scores[x][col];
        }
        faverage = (float)total / 10.0f;

        average = total = 0;
        AverageScore[x] = faverage;
    }
}

最佳答案

Though I am unable to figure out, how to sort that average.

我会使用 std::pair 将艺术家映射到乐谱。然后我会使用 std::sort 来实现排序:

#include <vector>
#include <utility>
#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<std::string> artists{ "Degas", "Holbien", "Monet", "Matisse", "Valesquez" };
    std::vector<std::vector<int>> scores{{ 3, 2, 1 }, { 5, 4, 3 }};

    std::vector<std::pair<std::string, int>> chart;

    for (auto name = artists.begin(); name != artists.end(); ++name)
    {
        for (auto score = scores.begin(); score != scores.end(); ++score)
        {
            int total = std::accumulate(score->begin(), score->end(), 0);
            int average = total  / score->size();
            chart.push_back(std::make_pair(*name, average));
        }
    }

    struct
    {
        bool operator()(std::pair<std::string, int> p1, std::pair<std::string, int> p2) const
        {
            return p1.second < p2.second;
        }
    } Predicate;

    std::sort(chart.begin(), chart.end(), Predicate);

    for (auto it = chart.begin(); it != chart.end(); ++it)
    {
         std::cout << it->first << ": " << it->second << std::endl;
    }
}

关于c++ - 在 C++ 中对列(数组)的平均值进行排序和打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838519/

相关文章:

c - 如何使用变量x来初始化数组?我知道我们不能在这里使用变量

c++ - 我不知道这个 C++ 单行代码的作用

c++ - C++中类似Java的默认构造函数的含义

c++ - ' ')' 错误之前的预期主表达式'

C++对许多项目使用数组或 vector

JQuery - 重新排列对象 - 最短代码解决方案

c++ - 在我的组合框中输入数据

javascript - Json 编码 数组与仅转换为数组的对象的混合

java - 如何从列表<String>中删除重复元素?

php - 删除除我想要的所有数组元素吗?