STL Revisited – mind the namespace

March 10, 2008

it’s been a while since I looked at stl. and this trip into stl and c++ native programming really brought me into senses once again. i built a simple project using stl, the program itself is very simple. i want to have a dictionary where entries can be looked-up using strings and the result is also in strings. only this time, i want it all to be in stl. i know that we can use map to do this, but to brush up my skills and to see the effect of composability, i used a list combined with a pair in the structure. it’s a one liner very easy. or so i thought.

 the problem arises when i tried to use find to get an entry. suddenly all hell break loose. all those cryptic stl error messages pouring down in my error window and it forced me to decrypt the messages one by one. the problem seems to originate from the inavailability of string operator==. so, i figured that the string operator== needs to be defined. no sweat. bool operator== ( const string& left, const string& right )… that should do it. but no, the error just wont get away. okay… maybe the pair operator== needs to be defined: bool operator== ( const pair<string, string>& left, const pair<string,string>& right )… no sweat.

again, i tried to recompile it, but the error just refuses to go away. what happened? doh… i tried various thing. i changed the pair to a pair of ints, it went smooth. i tried various combinations, i tried putting the find logic itself out from the funtion and put it in the source, but to no effect. after i tried for a while, i thought it is the time to try google. so i did. I surfed through the forums, but c’mon no forum will discuss this kind of problem specifically right? instead, i found a hint. written in a forum is a small advice: ‘put it inside the std namespace’. then it struck me! damn, i declared the operators outside the namespace! i put it inside the namespace cage, and… voila! everything works fine.

things that i learn:
1. mind the namespace.
2. decrypt stl messages by means of substitution, eg: basic_string<char, chartraits> = string
3. don’t blame the library. 99.99% of mistake is of your own doing (as i have written before)
4. respect the semantics.

about no.4, i have given a thought why string doesn’t have operator== defined. i dont have the full answer, but i guess it might be because of performance problem. or, because of semantic problem.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: