using maps of string *.

P

pmatos

Hi all,

I'm trying to use a map of string* and unsigned ints but results are
not good. I've used as example this piece of code:
http://www.sgi.com/tech/stl/Map.html

And I have done this:
#include <iostream>
#include <map>

using namespace std;

struct ltstr {
bool operator()(const string * s1, const string * s2) const {
return *s1 == *s2;
}
};

int main() {

map<const string *, unsigned int, ltstr> m;
const string * s1 = new string("Hello");
const string * s2 = new string("Buh");

m[s1] = 3;
m[s2] = 4;

const string * s4 = new string("Hello");

cout << "S4 VALUE: " << m[s4] << "\n";

delete s1;
delete s2;
delete s4;

return 0;
}


For some reason I get:
$ ./maptest
S4 VALUE: 0

Can't understand what's happening. I was expecting value 3. Shouldn't
*s1 == *s2 return true iff s1 and s2 are lexicographically equal?

Cheers,

Paulo Matos
 
K

Karl Heinz Buchegger

Can't understand what's happening. I was expecting value 3. Shouldn't
*s1 == *s2 return true iff s1 and s2 are lexicographically equal?

Yes, but this is not what map wants from you.
map wants a sorting predicate which represents 'less then'!
 
P

pmatos

Karl said:
Yes, but this is not what map wants from you.
map wants a sorting predicate which represents 'less then'!

Ah, how stupid of me. :) Eh, I just had to substitute *s1 == *s2 by *s1
< *s2. :) LOL Thanks. :D
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top