Consider a scenario where you are working with UNIX sockets. Sending/Receiving data across the network. Now, it is good practice to always send data as a “packet” instead of just array of char. Now following good practice of sending packet(structure/class) across the connection suppose we have a packet like this:
enum { DEFAULT, LOGIN } ;
struct packet {
char loginName[128] ;
unsigned int packetType ;
packet() {
memset(loginName, NULL, sizeof(loginName));
packetType = DEFAULT ;
}
} ;
Note that we can only use “primitive” data types inside this struct as we will be sending/receiving it across network. So if you try to write something like :
struct packet {
string loginName; // illegal if you try to send this across the network
} ;
If we are storing this loginName in a STL-map as key, then following the same types you may be tempted to define map as:
map<char *, int> loginInfo; // BIG MISTAKE
using char-pointer as key value is BIG MISTAKE. Although it is syntatically correct but it is evil. Let me show you an example to make my point clear:
char a[] = "Hello" ; char b[] = "Hello" ;loginInfo.insert(pair<char *, int>(a,1)) ; loginInfo.insert(pair<char *, int>(b,2)) ; // should not be added right. Since we // already have a key named // "Hello" in it. But it does add it
Run this code:
map<char *, int> :: iterator iter = loginInfo.begin() ;
while (iter != loginInfo.end()) {
cout<<iter->first<<endl;
iter++ ;
}
Output:
Hello
Hello
WEIRD ISNT’t IT.
The reason it adds the same key into the map is that it does not stores “Hello” as key in the first place. It just stores the “starting address” of “a” and starting address of “b”, which obviously happens to be different. Therefore, you end up having not quite same keys.
So correct way to do this is:
map<string,int> loginInfo ;
string tempA = a ;
string tempB = b ;
loginInfo.insert(pair<string, int>(tempA,1)) ;
loginInfo.insert(pair<string, int>(tempB,2)) ; // now OK. It won't insert the
// string tempB since key is
// already present.
Hope this will help some of you !
Sphere: Related ContentNo related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
