473,499 Members | 1,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

weirdness with std::map<const char *, int>

All,

Just wondering if one of you very helpful guru's out there could
comment on some odd behaviour I am seeing. I'm betting it is something
obvious but I am not experienced enough to tell right away. Here is my
code snippet and the results that I am seeing:

#include <map>
#include <iostream>
int
main(int argc, char *argv[])
{

string ids;
map<const char *, int> mytest;
ids = "john";
mytest[ids.c_str()] = 0;
ids = "james";
mytest[ids.c_str()] = 1;
map<const char *, int>::iterator it;
const char *id;

for (it=mytest.begin(); it != mytest.end(); ++it) {
cout << "-" << it->first << "-" << it->second << endl;
}

id = "john";
if (mytest.find(id) != mytest.end()) {
cout << "Found john" << endl;
}
id = "james";
if (mytest.find(id) != mytest.end()) {
cout << "Found james" << endl;
}
}

So this just creates a map container and populates it with a couple of
values. The key values are entered as strings converted to const char
* values. Running it, I would expect for it to dump out the contents
of the container and then find the entries. However, when I run it, i
just get the dump of the contents but none of my find() commands are
working.

-john-0
-james-1

So is the string.c_str() function doing something funny that I am not
taking into consideration?

Note I am running rhel4 using
gcc version 3.4.4 20050721 (Red Hat 3.4.4-2)

Thanks in advance.

Jan 5 '06 #1
4 11688

la****@yahoo.com wrote:
All,

Just wondering if one of you very helpful guru's out there could
comment on some odd behaviour I am seeing. I'm betting it is something
obvious but I am not experienced enough to tell right away. Here is my
code snippet and the results that I am seeing:

#include <map>
#include <iostream>
int
main(int argc, char *argv[])
{

string ids;
map<const char *, int> mytest;
ids = "john";
mytest[ids.c_str()] = 0; id = "john";
if (mytest.find(id) != mytest.end()) {
cout << "Found john" << endl;
} So is the string.c_str() function doing something funny that I am not
taking into consideration?


I think it probably has more to do with comparison operators on a char*
comparing address values.

Frankly, I'm surprised it doesn't crash.

Jan 5 '06 #2
la****@yahoo.com wrote:
All,

Just wondering if one of you very helpful guru's out there could
comment on some odd behaviour I am seeing. I'm betting it is something
obvious but I am not experienced enough to tell right away. Here is my
code snippet and the results that I am seeing:

#include <map>
#include <iostream>
You're missing <string>, and you need "using namespace std;" if you
don't want to qualify your names below.
int
main(int argc, char *argv[])
You don't use argc or argv. You can omit them altogether.
{

string ids;
map<const char *, int> mytest;
ids = "john";
mytest[ids.c_str()] = 0;
ids = "james";
mytest[ids.c_str()] = 1;
map<const char *, int>::iterator it;
const char *id;
First, there's no need to have all your variables declared at the top.
Prefer to declare them only when you need them and then in the smallest
possible scope, and always initialize them when you declare them.

Second, why don't you use a map<string,int>? I suspect that this is
where your problem is. Your map key is a pointer address, not a string,
and so when the map compares keys, it doesn't compare "john" and
"james"; rather it compares 0x8042365 and 0x20340500 (or whatever the
addresses are). If you use std::string that won't happen. Alternately,
you can supply the proper string comparison operator as the third
template parameter (see, e.g., http://www.sgi.com/tech/stl/Map.html).

I would suggest you replace these lines with:

map<string,int> mytest;
mytest["john"] = 0;
mytest["james"] = 1;

for (it=mytest.begin(); it != mytest.end(); ++it) {
Prefer something like:

typedef map<string, int>::const_iterator CI;
for( CI it = mytest.begin(); it != mytest.end(); ++it ) {
cout << "-" << it->first << "-" << it->second << endl;
}

id = "john";
if (mytest.find(id) != mytest.end()) {
cout << "Found john" << endl;
}
How about:

if( mytest.find("john") != mytest.end() ) {
id = "james";
if (mytest.find(id) != mytest.end()) {
cout << "Found james" << endl;
}
return 0;

Not strictly necessary, but good form nonetheless.
}

So this just creates a map container and populates it with a couple of
values. The key values are entered as strings converted to const char
* values. Running it, I would expect for it to dump out the contents
of the container and then find the entries. However, when I run it, i
just get the dump of the contents but none of my find() commands are
working.

-john-0
-james-1

So is the string.c_str() function doing something funny that I am not
taking into consideration?

Note I am running rhel4 using
gcc version 3.4.4 20050721 (Red Hat 3.4.4-2)

Thanks in advance.


Cheers! --M

Jan 5 '06 #3
Thanks for the quick reply and the code tips. I've gone with strings
and i'm much happier for it.

Jan 5 '06 #4

la****@yahoo.com wrote:
Thanks for the quick reply and the code tips. I've gone with strings
and i'm much happier for it.


99% of the time you will be happier with std::string rather than char*
or char[]. Yes, the later are faster (though not necissarily by much)
but unless your strings are static or absolutely bounded to a
particular size you don't want to have to mess with the problems
exhibited by bad char* or char[] code. Buffer overruns have undefined
behavior and in this case they usually really mean *undefined*...code
breaks in places seemingly totally unrelated sometimes and it can take
hours or days to hunt down. Even when you *think* your strings have an
absolute upper bound don't assume this is so...I myself spent hours
trying to find a problem that turned out to be an overrun because some
developer before me assumed an upper bound that seemed totally
rediqulous but when features changed, the length of the string
increased exponentially.

Most of the time your code will not be hindered in speed by the
std::string "problems" like reallocation and such...if you keep in mind
not to make unnecissary temporaries. The cost vs. benefit of
std::string is way way way weighted on the benefit side.

Jan 5 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
8720
by: Peter Jansson | last post by:
Hello, I have the following code: std::map<int,std::set<std::string> > k; k="1234567890"; k="2345678901"; //... std::set<std::string> myMethod(std::map<int,std::set<std::string> > k)...
13
4577
by: jstanforth | last post by:
This is probably a very obvious question, but I'm not clear on what operators need to be implemented for std::map.find() to work. For example, I have a class MyString that wraps std::string, and...
19
6117
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not...
2
2229
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It...
3
2615
by: tomix | last post by:
Hi, I have a domain model written with STL and a client which uses it I would like to give the client a better way to declare a container. Where is the best place to put all my typedefs? (typedef...
12
5804
by: jabbah | last post by:
Actually I'm quite sure I've missed something trivial here, but I just can't find it. Seemingly I cannot read from a const map& I try #include <iostream> #include <map> using namespace std;
2
2766
by: jabbah | last post by:
I have some data in a map and I want to sort it. Currently I have implemented it like this: #include <iostream> #include <map> #include <string> using namespace std; int main(){
6
5410
by: Juha Nieminen | last post by:
joseph cook wrote: Not always. By default, yes, but you can specify other comparators, eg: std::map<int, int, std::greaterreversedMap;
0
7009
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
5475
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4919
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4602
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3103
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3094
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
302
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.