Map "find" function wont work.

Hi,
I have a question that bugs me for days now. I have a piece of code of a map that has a char* for the key. And char* as value. Which looks like

typedef std::map<char*,char*,chchMapComp> chchMap;

And the comparison is done,

struct chchMapComp {
bool operator()(const char *a, const char *b) const {
return std::strcmp( a, b ) < 0;
}
};

When I run the program the data is populated properly. But its when I find for a element that puzzles me.

Initially I compiled the code through Visual Studio. The code worked fine. But when I compiled in Solaris using g++ the map find function didnt work as expected. The code compiles, in both machines. I dont know where I went wrong.

Someone please give me a clue..
I didn't see any such problems when running on solaris.

bash-3.2$ g++ -v
Using built-in specs.
Target: sparc-sun-solaris2.10
Configured with: /gccsrc/gcc-4.1.1/configure --prefix=/usr/local --enable-languages=c,c++
Thread model: posix
gcc version 4.1.1


here is the code I used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cctype>
#include <map>

using namespace std;

struct chchMapComp {
	bool operator()(char *a, char *b) {
		return strcmp( a, b ) < 0;
	}
};


int main()
{

	std::map<char*, char*, chchMapComp> chchMap;

	{
		char* key = "key1";
		char* value = "hello1";
		chchMap.insert(std::pair<char*, char*>(key, value));
	}
	{
		char* key = "key2";
		char* value = "hello2";
		chchMap.insert(std::pair<char*, char*>(key, value));
	}
	
	//chchMap.insert("key3", "hello3");
	//chchMap.insert("key4", "hello4");

	std::map<char*, char*, chchMapComp>::iterator iter = chchMap.find("key1");
	std::cout << iter->second << std::endl;


	return 0;
}

Thanks alot writetonsharma, the thing is when I hard code the key it gave me the required results. As you have done here.

But when I pass a char* to find method it gave me random results. I checked the value of the passd variable through VS2010 and found that the values are same.

char *val something like "C000003" when I cout in two different instances as shown in code below,

cout<<"--"<<val<<"--"<<endl;

On windows it gave me
--C000003--
but on Solaris
--C000003

As you can see the las two "--" isnt printed. So I had doubts in the char* that I was passing.
¿why don't use a debugger to see the variable?
Probably the problem is in your code, you may post it.

If you are reading from a file, keep in mind the different line terminators
\r\n, \n, \r
as ne555 said, you will have to post more code. It must be in your code only.
Topic archived. No new replies allowed.