2012-11-13 152 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」參數就足夠了。如果你沒有,我認爲,你需要指定的,而不是「大」

相關問題