2016-08-19 73 views
1

當前創建的一段代碼能夠從文本文件輸出,我正在讀取文本並將每條不同的信息放入數組中。使用相應的數組對數組進行排序

我已經使用了4個不同的數組,因爲我想存儲4種不同類型的信息。這個代碼的工作方式和預期的一樣,但我不確定如何按照字母順序對數據進行排序,並且所有相應的數組都保持一致並在正確的時間輸出。

void displayfile(){ 

string filename1; 
string rartist[NUM]; 
string rtitle[NUM]; 
string ryear[NUM]; 
string rcategory[NUM]; 
ifstream openFile; 
int counter = 0; 
int continu 
bool error = false; 
cout << "test"; 

do{ 
    //Loop to retrieve the file name from user, then open file 
    do{ 
     cout << "Please enter the name of the menu you would like to open: "; 
     cin >> filename1; 
     filename1 += ".txt"; 
     openFile.open(filename1.c_str()); 
     if(openFile.fail()){ 
      cerr << "Check spelling of file name.\n"; 
      error = true; 
     } 
    //Storing text from file into arrays 
    }while(error == true); 
    while(getline(openFile, rartist[counter], ':') && getline(openFile, rtitle[counter], ':') && 
     getline(openFile, ryear[counter], ':') && getline(openFile, rcategory[counter])){ 
    counter++; 
    } 
    //outputting the information stored in the array 
    cout << "ARTIST " << " DVDTITLE " << " YEAR " << " CATEGORY \n"; 
    for(int i = 0; i < counter; i++){ 
     cout << rartist[i] << "    " << rtitle[i] << "    " 
      << ryear[i] << "    " << rcategory[i] << "\n"; 
    } 
    cout << "\n\nIf you would like to read another file, Press 1: "; 
    cin >> continu; 
    }while(continu == 1) 
} 

這是我用來顯示當前文本的功能。

+1

最簡單的方法是讓你有含有相關項,而不是針對每個項目類型的單獨陣列結構的一個單個陣列來重組數據。 –

+0

這可能是我需要的,因爲我保留此功能並創建一個新的功能來進行排序,作爲另一種選擇。謝謝你現在看看這個。 – Thecube

回答

3

我假設您正在閱讀有關歌曲的信息,並且您想根據歌曲標題對其進行排序。由於您正在爲每首歌曲讀取相同類型的數據,因此請使用單個結構數組,而不是單獨的數組。

例如,這是如何按歌名排序歌曲。

struct Song { 
    std::string artist, 
    std::string title, 
    std::string year, 
    std::string category 
}; 

std::vector<Song> songs(NUM); 

// Read data 

std::sort(songs.begin(), songs.end(), 
    [](const Song &a, const Song &b) { 
     return a.title < b.title; 
    }); 
+0

我可以使用循環將結構存儲到結構中嗎? – Thecube

+0

當然。不用'rartist [i]',使用'songs [i] .artist'。 – Nelfeal

1

完全未經測試C++ 11代碼

std::vector<int> indexes(NUM); 
// fill with 0..NUM-1 
std::iota(indexes.begin(), indexes.end(), 0); 

// example sort after artist. 
std::sort(indexes.begin(), indexes.end(), 
    [&rartist](const int &lhs, const int &rhs) { 
     return rartist[lhs] < rartist[rhs]; 
    }); 
// indexes is now sorted in the same way rartist would have been. 

// now iterate in order. 
for (int i : indexes) { 
    std::cout << rartist[i] << "    " 
       << rtitle[i] << "    " 
       << ryear[i] << "    " 
       << rcategory[i] << "\n"; 
} 
+0

您可能也對['std :: iota']感興趣(http://en.cppreference.com/w/cpp/algorithm/iota)。 – Jarod42

+0

*對於範圍*似乎比'std :: for_each'更自然 – Jarod42

+0

@ Jarod42,我不會不情願地想你的權利。 – Surt