在C++中对列(数组)中的平均值进行排序和打印
Sort and Print Average Values from Column (Array) in C++
我能够从 2D 数组(列)生成平均值。虽然我无法弄清楚,如何对这个平均值进行排序。我必须创建一个新数组(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 << "nnt-------------------------------------------" << endl;
cout << "ttRanking 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 << "nt" << Artist[x] << "tt";
for (int col = 0; col < A2_COLSIZE; col++)
{
total+=Scores[x][col];
}
faverage = (float)total / 10.0f;
average = total = 0;
AverageScore[x] = faverage;
}
}
虽然我无法弄清楚,如何对这个平均值进行排序。
我会使用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;
}
}
您可以使用
std::sort
对rankedscore数组进行排序。之后,只需制作一个 for 循环并打印其值。
您可以在此处查看如何使用std::sort
的示例
编辑:由于RankedScore和艺术家应该是相关的,你可以使用地图结构。使用平均分数作为关键。然后,您可以按键对地图进行排序,并按顺序打印键值(艺术家)。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 计算数组c++的平均值
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 在C++中对列(数组)中的平均值进行排序和打印
- 编写一个程序,读取所有命令行参数并打印平均值 c++