gpt4 book ai didi

c++ - 使用相应的数组对数组进行排序

转载 作者:行者123 更新时间:2023-11-30 01:42:45 25 4
gpt4 key购买 nike

目前创建了一段能够从文本文件输出的代码,我正在阅读文本并将每条不同的信息放入一个数组中。

我使用了 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)
}

这是我当前用来显示文本的函数。

最佳答案

我假设您正在阅读有关歌曲的信息,并且希望根据歌曲名称对它们进行排序。由于您正在为每首歌曲读取相同类型的数据,因此请使用单个结构数组,而不是单独的数组。

例如,这就是您按标题对歌曲进行排序的方式。

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;
});

关于c++ - 使用相应的数组对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39048148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com