std::map m;
m[k] = v;
std::map m;
m[k] = v;
std::map m;
m[k] = v;
std::list<RoomData*> *r_list;
class Room {
public:
operater [] (int vnum) { <insert itteration here> }
}
$ cat op.cpp
#include <iostream>
using namespace std;
template<typename T>
struct S
{
operator T() const;
T* obj;
};
template<typename T>
S<T>::operator T() const
{
return *(this->obj);
}
int main()
{
S<int> s;
int i = 1;
s.obj = &i;
int &j = s;
cout << s << endl;
j = 2;
cout << s << endl;
return 0;
}
$ g++ op.cpp
op.cpp: In function 'int main()':
op.cpp:24: error: invalid initialization of reference of type 'int&' from expression of type 'S<int>'
class my_map_key_exception {
// blah
};
template <typename _Key, typename _Value> class my_map : public std::map<_Key, _Value> {
public:
void set (const _Key& key, const _Value& value) {
insert(std::pair<_Key, _Value>(key, value));
}
const _Value& get (const _Key& key) const {
const_iterator i = find(key);
if (i == end())
throw new my_map_key_exception();
return i->second;
}
_Value& get (const _Key& key) {
iterator i = find(key);
if (i == end())
throw new my_map_key_exception();
return i->second;
}
bool has_key (const _Key& key) const {
return find(key) != end();
}
};
#include <string>
#include <map>
using namespace std;
int main(int argc, char**argv) {
map <string, int> testme;
testme["foo"] = 1;
testme["bar"] = 2;
cout << "size == " << testme.size() << endl;
cout << "testme[foo] == " << testme["foo"] << endl;
cout << "testme[ack] == " << testme["ack"] << endl;
cout << "size == " << testme.size() << endl;
map <string, int> ::iterator i = testme.begin();
i = testme.find("pfft");
if (i != testme.end())
do {
cout << "testme[pfft] == " << i->second << endl;
} while (++i != testme.end());
else
cout << "testme[pfft] is not defined." << endl;
cout << "size == " << testme.size() << endl;
}
Much to my surprise!
size == 2
testme[foo] == 1
testme[ack] == 0
size == 3
testme[pfft] is not defined.
size == 3
I wasn't aware that trying to reference an element of a std::map container that hadn't been defined yet, resulted NOT in the exception I expected, but rather created the entry on the fly, and gave it whatever default empty value the data type in question has.
While that can be good for some things, it's kindof bad for others. Consider, the prime application I see for std::map is for the room/mob/obj lists. Being able to refer to room[3001] directly, instead of pawing through a list or tree, is enormously helpful.
However, as the above shows, it's not as handy as I had hoped! If a wizard types "goto 3002", I can't just look to see if room[3002] exists by seeing if it's defined… I have to declare an iterator and do room.find(3002), otherwise it WILL exist (and be an empty room). Hrmph.