关于自定义比较函数的问题

saramand9 2008-03-23 01:24:56
#include<iostream>
#include<map>
#include<string>
using namespace std;

class KeyComp
{
public:
bool operator()(const string& gs1, const string& gs2) const
{
return gs1 > gs2;
}
};

int main(int argc, char* argv[])
{
typedef std::map<string, int, KeyComp> test;
map<string , int ,KeyComp > S;
S["2134"]=3;
S["323"]=4;
map<string , int ,KeyComp >::iterator p;
for(p=S.begin();p!=S.end();p++)
cout<<(*p).first<<endl;
return 0;
}


我知道的自定义函数大概有三种..其他两种还有 ... sort函数的 ..直接写个bool型的比较函数..
或者是在对象中重载 < 或 > 符号来达到自己需要的效果...但是这种从来没见过...不知道是怎么理解的..
或者哪位朋友知道这个知识点可以在什么书中找到...谢啦
...全文
102 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
saramand9 2008-03-23
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 jieao111 的回复:]
可是第三个参数怎么理解呢,,为什么输出是
323
2134
不是返回较大的吗
[/Quote]

呵呵..."323" 不是比 "2134" 大的吗...
因为他们是string 那
ttkk_2007 2008-03-23
  • 打赏
  • 举报
回复

//函数对象,也叫仿函数类,你可以把它做成可适配的,具体参考msdn
class KeyComp : public binary_function<string, string, bool>
{
public:
bool operator()(const string& gs1, const string& gs2) const
{
return gs1 > gs2;
}
};
jieao111 2008-03-23
  • 打赏
  • 举报
回复
可是第三个参数怎么理解呢,,为什么输出是
323
2134
不是返回较大的吗
jieao111 2008-03-23
  • 打赏
  • 举报
回复
函数对象
  • 打赏
  • 举报
回复
关于map默认的比较函数
Traits
The type that provides a function object that can compare two element values as sort keys to determine their relative order in the map. This argument is optional and the binary predicate less<Key> is the default value.

最好查一下MSDN,不一定只有这几种的.
野男孩 2008-03-23
  • 打赏
  • 举报
回复
这个KeyComp是个函数对象。因为map是泛型容器,所以没把法提供具体的比较函数对放入的任意类型进行比较排序。所以对于非内置的类型,应该提供其比较的方法,map才能正确的排序。

看看<c++ primer>吧
xhd3767 2008-03-23
  • 打赏
  • 举报
回复
应该是重载操作符!然后在map中调用!但是参数是两个.......关注中

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧