2016-08-19 6 views
1

現在、テキストファイルから出力できるコードを作成しました。テキストを読み込み、それぞれの情報を配列に格納しています。配列を対応する配列で並べ替える

私は保存したい4種類の情報があるので、私は4種類の配列を使いました。このコードは期待どおりに動作していますが、配列の1つをアルファベット順に並べ替える方法で情報を並べ替える方法は不明です。対応するすべての配列が正しいタイミングで出力されて出力されます。

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