2016-09-16 93 views
-6

我剛剛完成作業,但最後一節正在殺死我。我已經完成了研究,解決方案是我們在課堂上沒有教過的概念,並且完全凌駕於我的頭上。我需要bubbleSort和結構數組。但是我完全失去了。任何幫助將不勝感激。氣泡排序結構數組

#include "stdafx.h" 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <algorithm> 

struct billingInfo; 
void bubbleSort(billingInfo list[], int length); 
using namespace std; 

int main() 
{ 
    // create struct with a field for zip codes and name of recepients that are being imported from text document 
     struct billingInfo { 
     int zipCode; 
     string name; 
    }; 

    // create array of billingInfo struct 
    billingInfo recipients[20]; 

    // open text file and test if file opened 
    ifstream dataFile("NameZip.txt"); 

    if (dataFile.fail()) 
     cout << "Can't open file." << endl; 
    else cout << "File opened." << endl; 

    int numElements = 0; 
    while (dataFile.peek() != EOF) { 
     dataFile >> recipients[numElements].zipCode; 
     getline(dataFile, recipients[numElements].name); 

     cout << recipients[numElements].zipCode << endl; 
     cout << recipients[numElements].name << endl; 
     numElements++; 
    } 

    system("pause"); 

    return 0; 
} 

void bubbleSort(billingInfo list[], int length) { 
    billingInfo temp; 
    int itterator; 
    int index; 
    for (itterator = 1; itterator < length - itterator - length; itterator++) { 
     for (index = 0; index < length - itterator; index++) { 
      temp = list[index]; 
      list[index] = list[index + 1]; 
      list[index + 1] = temp; 
     } 
    } 
    enter code here 

} 
+0

究竟什麼是您所遇到的問題?此外,這不是如何拼寫迭代器 – xaxxon

+0

「_Bubble對結構數組進行排序」 - 「struct」是引用數據類型,因此此類型的變量(對象)沒有可用作參數的原始可比較值進行分類。你將不得不根據struct的成員變量的值來評估'struct'對象。在你的代碼中,唯一的數字值由'int zipCode'保存。你究竟如何排序?是否應該按照郵政編碼的值升序/降序排列? – progyammer

+0

對不起,太模糊了。我將按照字母順序排列字段名稱,排序爲 –

回答

0
struct billingInfo 
{ 
    int key; // Can be any key 

}; 
typedef struct billingInfo billingInfo; 

// Overload the > operator 
bool operator> (const billingInfo& first,const billingInfo& second) 
{ 
    return first.key > second.key; 
} 

// Make a custom Swap function for your struct 
void swap (billingInfo& first,billingInfo& second) 
{ 
    int temp; 
    temp = first.key; 
    first.key = second.key; 
    second.key = temp; 
} 

// Not a single line of change in Bubble Sort Code. 
// I hope the below code is bubble sort :p 
void bubble_sort (billingInfo *list,int length) 
{ 
    for (int i=0;i<length-1;i++) 
     for (int j=0;j<length-i-1;j++) 
      if (list[j] > list[j+1]) // will work since we overloaded 
       swap (list[j],list[j+1]); // Our custom function 
} 
+0

如果您發現該字段正確,請接受並提供答案。 – PRP