473,221 Members | 2,395 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,221 software developers and data experts.

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 11667

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
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
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
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
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
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
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
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
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
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

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.