So, I know some Python but I thought that I should try to add some c++ to that knowledge. This is the code I’ve written that I’m playing with (it’s actually a rewrite of some python code). It adds some song data to a class (or a multidimensional array inside a class). So far so good. Most of it work. But I’m stuck at the delSong method. I don’t think I could implement this with arrays, so It’s seems like I’m at a dead end. I read a little about vectors, but they won’t let med delete an item in the middle. How could I get further? Shall I abandon arrays for something else? But what would that be?
#include <iostream>
#include <string>
using namespace std;
class Jukebox{
public:
void addSong(string artist, string title, string filename) {
songs [songsCounter][0] = artist;
songs [songsCounter][1] = title;
songs [songsCounter][2] = filename;
songsCounter++;
}
void printSong (int song) {
cout << songs[song][0] << " - ";
cout << songs[song][1] << " : ";
cout << songs[song][2] << endl;
}
void printSongs () {
int song;
for (song=0; song<songsCounter; song++ ) {
cout << songs[song][0] << " - ";
cout << songs[song][1] << " : ";
cout << songs[song][2] << endl;
}
}
void delSong(int song) {
// Some code here
}
private:
int songsCounter;
string songs [512][3];
};
int main() {
Jukebox jbox;
jbox.addSong("U2", "Magnificent", "U2-Magnificent.mp3");
jbox.addSong("Sting", "Englishman in New York", "Sting-Englishman_in_New_York.mp3");
jbox.addSong("U2", "One", "U2-One.mp3");
jbox.printSongs();
return 0;
}
In my python code I actually using an in memory sqlite3 db. But I could as well write it with a simple list of tuples. And that is a similar approach to what I’m trying to do here. But an in memory sqlite database would also be a possible way for me to do this in c++. But it does’nt look very easy either to implement?
One more thing, I also want to add a sort method later so please have that in mind when you suggest a solution so I don’t get to another dead end… 🙂
Vectors do allow deletion in the middle (look for the
erasefunction), albeit not at the greatest speed.I’d recomend using a vector of structures instead of a multidimensional array.
And then in your
Jukebox:The vector grows as needed and keeps track of its own size, contrary to the array.
For sorting, there’s
std::sortfunction in the<algorithm>header.