2016-08-19 68 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