|
-
February 20th, 2009, 05:21 AM
#1
Please help how to create a C++ stl map that takes a comparison function?
This is what I tried but when I retrieve from the map I get nothing:
#include <iostream>
#include <map>
using namespace std;
struct strCompare
{
strCompare(){}
bool operator()(const std::string& str1,const std::string& str2)const
{
return str1.compare(str2)<=0;
}
};
typedef std::map<std::string, std::string, strCompare> mymap;
int main()
{ mymap m = mymap();
m["abc"]="def";
std::cout<<m["abc"];
}
-
February 20th, 2009, 05:34 AM
#2
Re: Please help how to create a C++ stl map that takes a comparison function?
 Originally Posted by BarefootGuy
This is what I tried but when I retrieve from the map I get nothing:
1) Please use code tags when posting code.
2) Your compare function is wrong. You never return the same value for less than and for equal to. You are returning true for both less than and equal. Correction:
Code:
return str1.compare(str2) < 0;
The reason is that the comparison follows a strict weak ordering. Two values comparing equal is never used in the ordering. It's either compare less than and return true/false, or compare greater than and return true/false. Comparing for equality and returning true/false is the one bug that a lot of programmers make when they write their comparison functions.
Regards,
Paul McKenzie
-
February 20th, 2009, 05:34 AM
#3
Re: Please help how to create a C++ stl map that takes a comparison function?
The problem is with your comparator: it says that if str1 is less than or equal to str2, then str1 is "less than" str2. Rather, the predicate used in such comparisons must provide a "strict weak ordering".
Suppose we have a strCompare object named cmp. Then for strict weak ordering to hold, and given some strings a, b and c:
- cmp(a, a) must be false.
- if cmp(a, b) is true then cmp(b, a) must be false
- if cmp(a, b) is true and cmp(b, c) is true then cmp(a, c) must be true
By the way, please post your well indented code in [code][/code] bbcode tags.
-
February 20th, 2009, 05:38 AM
#4
Re: Please help how to create a C++ stl map that takes a comparison function?
Another bug is that you didn't include <string>.
Regards,
Paul McKenzie
-
February 20th, 2009, 07:52 AM
#5
Re: Please help how to create a C++ stl map that takes a comparison function?
I find this book to be of great help on how to use the C++ standard library,
http://www.josuttis.de/libbook/index.html
But note that it's from 1999 and I'm quite sure there will be a new edition very soon after the new C++ standard arrives next year. So it's probably better to borrow a copy or buy a used copy for the time being.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|