如何从文本文件中按升序对数据进行排序

How do I sort data in ascending order from a text file?

本文关键字:数据 排序 升序 文本 文件      更新时间:2023-10-16

我对c++编程还很陌生,我需要帮助编码,将文本文件中的数字按升序排序,这样我就可以得到它的中值,但我不知道如何做到这一点。

这是我到目前为止的代码:

//Create a Vector to hold a set of exam scores.Write a program to do the following tasks: 1. Read exam scores into a vector from Scores.txt 
//2. Display scores in rows of five(5) scores.
//3. Calculate average score and display.
//4. Find the median score and display.
//5. Compute the Standard Deviation and display
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int main ()
{   const int array_size = 36; // array size
int numbers[array_size]; //array with 36 elements
int count = 0;
int column_count = 5;
ifstream inputfile; //input file into stream object
//open file
inputfile.open("Scores.txt");
//read file
while (count < array_size && inputfile >> numbers[count])
count++;
//close file
inputfile.close(); 
//display numbers read
for (count = 0; count < array_size; count++) {
cout << numbers[count] << " ";
if ( count % column_count == column_count - 1 ) {
cout << "n";
}
}
//find the average
double average; //average
double total = 0; //initialize accumulator
cout << "nAverage:n";
for (count = 0; count < array_size; count++)
total += numbers[count];
average = total/array_size;
cout << average << " ";
cout << endl;
//find the median
std::sort(numbers.begin(), numbers.end(), std::greater<int>());


system ("pause");
return 0;
}

提前感谢!

您可能在不了解其真正含义的情况下从某处复制了这一行:

std::sort(numbers.begin(), numbers.end(), std::greater<int>());

由于使用的是正则数组,所以第一个参数是指向数组中第一个位置的指针。第二个参数是指向数组中最后一个元素后一个元素的指针。第三个参数指示数组应该按哪个方向排序(在您的情况下,您希望找到中值,所以方向无关紧要)。对于长度为array_size的数组,新函数调用被重写为:

std::sort(&(numbers[0]), &(numbers[array_size]), std::greater<int>());

当将数组传递给函数时,它们会自行衰减为指针。因此,您不需要使用&运算符。函数调用可以简化为:

std::sort(numbers, numbers + array_size, std::greater<int>());

在这种情况下对数据进行排序的目的是找到中值。不管数组是升序还是降序排序,中间元素的平均值都是相同的。如果您进一步使用了需要按升序排序的数组,请将第三个参数更改为std::less<int>()(或完全删除)。这将导致数组按升序排序。

std::sort(numbers, numbers + array_size);
#include <algorithm>
// ...
std::sort( numbers, numbers + array_size );

有关std::sort(…)函数,请参阅http://www.cplusplus.com/reference/algorithm/sort/.对于您的问题,您正在处理内置类型。std::sort的第一个重载版本不带"Compare"参数就足够了。如果你不这样做,我认为你需要指定"更少"而不是"更大">