所以我试图找出一个类的程序,我需要模拟一个播放列表,可以在音乐库中添加和删除歌曲,在播放列表中添加和删除歌曲等。
我有一个Song类和一个播放列表类,一个矢量库(用于歌曲库),以及一个包含vecto songList的矢量播放列表。如果我想从库中删除一首歌并在库矢量中给出一个歌曲指针的索引,我该如何检查该“歌曲”是否在任何“播放列表”中?这是我的相关代码部分:
using namespace std;
class Song {
public:
Song(string title, string line, int count) {
name = title;
firstLine = line;
playCount = count;
}
string GetName() {
return name;
}
string GetFirstLine() {
return firstLine;
}
private:
string name;
string firstLine;
int playCount;;
};
class Playlist {
public:
Playlist(string name = "none"){
pName = name;
}
void AddSong(Song* song) {
songPtr.push_back(song);
}
void RemoveSong(int songIndex) {
songPtr.erase(songPtr.begin() + songIndex);
}
string GetSongAtIndex(int index) {
return (songPtr.at(index))->GetName();
}
private:
string pName;
vector<Song*> songPtr;
};
int main() {
string userIn;
vector<Song*> library;
vector<Playlist> playlists;
// code for adding songs to library using "new"
// code for adding songs to playlist using "new"
// delete song from library
// first, list songs in library
size = library.size();
for (i = 0; i < size; i++) {
cout << " " << i << ": " << (library.at(i))->GetName();
cout << endl;
}
// have user pick wich song they want erased
cout << "Pick a song index number: ";
cin.clear();
cin >> sIndex;
// FIXME: check if song is in any playlist, and if it is, remove it
string songName = (library.at(sIndex))->GetName();
int size = playlists.size(); //remove song from playlists
for (i = 0; i < size; i++) {
int size2 = (playlists.at(i)).GetPSize();
for (j = 0; j < size2; j++) {
string tempName = (playlists.at(j)).GetSongAtIndex(j);
if (tempName == songName) {
(playlists.at(i)).RemoveSong(j);
}
}
}
// code to delete song from library and free the memory
我有什么不起作用,当我在删除它后尝试列出库中的歌曲时,它会给我一个“超出范围”的错误并导致程序崩溃。当我评论出关于在播放列表中找到它的部分时,它从库中删除就好了。只有当我尝试检查该歌曲是否在播放列表中时才会出现错误。我对编程比较陌生,所以很可能我错过了一些东西,但我不知道如何解决这个问题。
答案 0 :(得分:0)
如果从播放列表中删除元素,则不应增加索引并减小大小:
// check if song is in any playlist, and if it is, remove it
string songName = library.at(sIndex)->GetName();
int size = playlists.size(); //remove song from playlists
for (j = 0; j < size2; ) { // do not increment j here
string tempName = playlists.at(i).GetSongAtIndex(j); // i, not j for playlists.at()
if (tempName == songName) {
playlists.at(i).RemoveSong(j); // j remains the same
--size2; // one element less
} else {
++j; // increment here
}
}