I also wanted to know, what does an iterator in a map or a vector holds? i mean is an iterator a pointer? does it hold address or value? |
Sort of. An iterator is very similar to a pointer. The main difference is that when you increment an iterator, it intelligently traverses the container, whereas when you increment a pointer, it blindly just advances to the next physical address whether it's valid or not.
now i want to access a random node and display it, say i want to play (cout) a random song out of x (which holds singer name and name of the song..) |
You should not use a map for that.
Map are designed to have a "key" and "value" pair for each entry. The idea is that you can quickly look up a value by providing its key.
For a singer/song combo, you appear to be using the singer as they key... which only makes sense if you have a singer name and need to use it to look up their song.
On top of that, map does not do random access well. If you need random access, consider a vector (or a deque, but vector is typically better).
i did like this and doesn't compile of course and i can't figure out a solution: |
Right, the error is that you cannot add to a map iterator like that because maps do not have random access. You would have to traverse the map one element at a time. Again, this is probably where map is at its weakest and you probably should not be using map if you need to access it this way.
Make a struct, and throw that struct in a vector:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
struct SongInfo
{
string singer;
string song;
};
vector<SongInfo> x;
// ...
int i = rand() % 5;
auto& itr = x.begin() + i;
cout << itr->singer << " " << itr->song;
|