使用相应的数组

时间:2016-08-19 21:50:09

标签: c++ arrays sorting

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

我使用了4种不同的数组,因为我想存储4种不同类型的信息。这个代码正在按预期工作,但我不确定如何以一种方式对信息进行排序,其中一个数组按字母顺序排序,所有相应的数组保持一致并在正确的时间输出。 / p>

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

这是我用来显示当前文本的功能。

2 个答案:

答案 0 :(得分: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;
    });

答案 1 :(得分: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";
}