Hello,
recently I stumbled upon the <map> library. With its possibility to make associative arrays, it fits perfectly into the game server I'm working on. (every player should have a unique ID, though, not every player is always online, so a map can easily free up the unused memory)
When a player leaves, the mapped element of the player's socket has to be removed. The problem is I only have a pointer to his socket (which is the
value of an element), so I can't just use the erase() function.
Instead, I tried to make a template function to give back the iterator pointing to the element (erase only allows key indices or iterators):
1 2 3 4 5 6 7 8
|
template<class T, class U> map<T, U>::iterator value_get_iterator(map<T, U> &themap, const U &value)
{
map<T, U>::iterator it;
for (it = themap.begin(); it != themap.end(); it++)
if (it->second == value)
break;
return it;
}
|
Unfortunately this failed, because the compiler doesn't understand the return value is a "map<T, U>::iterator".
I got better luck with putting the iterator in a typedef, but without the template:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <string>
#include <map>
using namespace std;
//In this case the element values are strings and are indiced by integers
typedef map<int, string>::iterator IT;
IT value_get_iterator(map<int, string> &themap, const string &value)
{
IT it;
for (it = themap.begin(); it != themap.end(); it++)
if ((it->second) == value)
break;
return it;
}
int main()
{
map<int, string> mymap;
mymap[ 0] = "some element value";
mymap[10] = "blah";
string findstr = "blah";
cout << "mymap[0] is " << mymap[0] << endl;
cout << "mymap[x] is 'blah' for x = " << value_get_iterator(mymap, findstr)->first;
return 0;
};
|
Though, as I said above, it doesn't use a template, so the function has to be overloaded and rewritten for every map type (which wouldn't be too hard for my current project, but I love generalising :P).
As you might have figured out, my question is: how do I apply this function to every map type?