如何从文本文件中按升序对数据进行排序
How do I sort data in ascending order from a text file?
我对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"参数就足够了。如果你不这样做,我认为你需要指定"更少"而不是"更大">
相关文章:
- 如何对点云数据进行排序
- 如何使用 QSortFilterProxyModel::sort 对 Qlist 中的数据进行排序
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 使用选择排序对数组数据结构进行排序,但它不起作用
- 为什么我的代码没有对数组中第二个索引上的数据进行排序?
- 使用 QSortFilterProxyModel 对 Qml ListView 的数据进行排序
- 读取 C++ 中的 txt 数据,展开为行或列并排序
- C++ 从文件中获取数据时使用 strcpy 和 strcmp 按字母顺序对数组进行排序?
- 存储在 std::map/std::set 中,与在存储所有数据后对向量进行排序
- 尝试创建排序的动态列表(数据结构)
- 固定大小的容器,其中元素被排序,并可以为C 中的数据提供原始指针
- 排序算法,使用模板按内部数据对对象进行排序
- 对多个数据成员进行排序
- 递归定义数组中的数据对齐和排序
- 如何修复输出显示,以便显示正确排序的数据
- 为什么我的气泡排序不适用于双精度数据类型?
- 气泡排序不传递数据或不起作用
- 使用 stl::map 和 stl::unordered_map 对包含大量重复元素的数组数据进行排序
- 数据排序依据是哪一列,QTableWidget
- 寻找更好的数据排序方法