2012-11-13 151 views
0

我对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; 
} 

谢谢!

+2

您是否必须自己编写排序算法? – evanmcdonnal

+0

请发表您试过的内容吗? – user93353

回答

1

你可能复制从某处这条线不理解“少”它真正的意思:

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

由于您使用常规数组,第一个参数是指向数组中第一个位置的指针。第二个参数是指向数组中最后一个元素的指针。第三个参数表明数组应该在哪个方向排序(在你的情况下,你想找到中位数,所以方向无关紧要)。

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

当通过阵列功能,它们衰变到自己的指针:为了您的数组被叫号码与array_size的长度,作为新的函数调用被重写。因此,您不需要使用&运算符。函数调用可以简化为:

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

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

std::sort(numbers, numbers + array_size); 
+0

-1对于OP所要求的“升序”,这个答案是(正如我发布这条评论)不正确,因为它按降序排列。我的答案很短,说明如何正确地做到这一点。用较短的代码。 –

+0

@ Cheersandhth.-Alf好点,但在这个问题中排序数据的目的是找到中位数。无论对数组进行升序还是降序排序,中间元素的平均值都是相同的。如果你需要按升序对数组进行进一步的使用,将第三个参数改为'std :: less ()'(或者完全删除它)。它会导致数组按升序排序。 – Ryan

+0

答案(因为我正在写这个)只是不正确的,因为它按降序排列而不是*升序排列。取消订单对于给定的目的是有用的:问题直接要求升序。更重要的是代码可以纠正更少!而不是指出它可以纠正,为什么不纠正呢。 –

1
#include <algorithm> 

// ... 
std::sort(numbers, numbers + array_size); 
0

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

相关问题