473,520 Members | 2,580 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 11693

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
8723
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) throw(std::runtime_error)
13
4584
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 which also implements ==, <, <=, >, >=, etc. (Those operators are tested and working correctly.) If I assign map = "world", it saves the...
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 found anything). Here's the problem, I have two sets of files, the name of a file contains a number which is unique for each set but it's possible...
2
2234
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 uses map<and heavy overloading. The problem is, the output file differs from input, and for the love of me I can't figure out why ;p #include...
3
2617
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 list <EnrollInfoEnrollInfoList) Thanks in advance.
12
5811
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
2771
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
5412
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
7318
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7230
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7458
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7623
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7198
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5763
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4804
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
851
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
525
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.