problem with map

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Mohammad Mahmudur Rahman
Experienced poster
Posts: 154
Joined: Sat Apr 17, 2004 9:34 am
Location: EEE, BUET

problem with map

Post by Mohammad Mahmudur Rahman » Wed Mar 02, 2005 6:16 pm

Hi,
The STL Map is driving me mad. :o
Can someone tell me why the following program -

Code: Select all

#include<iostream>
#include<cstring>
#include<map>
using namespace std;

struct ltstr
{
	bool operator()(const char *s1, const char *s2) const
	{
		return (strcmp(s1,s2)<0);
	}
};

int main(void)
{
	int i;
	char buf[100];
	map<const char *,int,ltstr> mp;

	for(i=0;i<5;i++)
	{
		cin>>buf;
		mp[buf] = i + 1;
	}

	for(i=0;i<5;i++)
	{
		cin>>buf;
		if(mp.find(buf)!=mp.end())
			cout<<mp[buf]<<endl;
	}

	return 0;
}//end main()
should produce -

Code: Select all

5
5
5
5
5
instead of -

Code: Select all

1
2
3
4
5
You should never take more than you give in the circle of life.

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Wed Mar 02, 2005 11:58 pm

buf is just a memory address. It stays the same in each iteration of your loop. You should use strings instead or create a new buffer for each input string (which is a bad idea as you're not familiar with pointers).

Mohammad Mahmudur Rahman
Experienced poster
Posts: 154
Joined: Sat Apr 17, 2004 9:34 am
Location: EEE, BUET

Post by Mohammad Mahmudur Rahman » Thu Mar 03, 2005 7:34 pm

Thanks for your reply. As I am not very accustomed with the use of STL, I was almost certain that there's something wrong with my STL structure & in the process, forgot the basic pointer behaviour. Thanks again for pointing it out. :P
You should never take more than you give in the circle of life.

Post Reply

Return to “C++”