stl中set 比较函数问题

lijinfenghust 2009-02-17 11:08:59
遇到个问题,就是定义set中比较函数的时候,直接return 1.(作用是不按照大小排序,而是按照先后插入的顺序排序)
运行时断言错误,请问原因?(不能用vector来替代这里的set)

#include "stdafx.h"
#include <assert.h>
#include <set>
using namespace std;

class compareInt
{
public:
bool operator()(const int &a,const int &b)
{
return 1;//如果是return a<b,就正确了,但这么写为啥不对。
}
};

int _tmain(int argc, _TCHAR* argv[])
{
set<int,compareInt> st1;
st1.insert(1);
st1.insert(-1);
return 0;
}
...全文
546 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
FanTasyCC 2009-02-17
  • 打赏
  • 举报
回复
8楼说的对,但这不是问题
插入的时候如果发现左右,右左都false的话,就是当成相等,所以-1不会存放进去,这没有问题
所谓的原则就是传递规则
(x < y) && !(y < x) 就是相等
(x < y) && (y < z) 那么一定是x < z
waizqfor 2009-02-17
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 lijinfenghust 的回复:]
vs2005 开发环境
[/Quote]
我这没问题啊 拿VC6和DEV-C++ 没VS2005的环境
我想跟你说的排序没有关系
lijinfenghust 2009-02-17
  • 打赏
  • 举报
回复
我终于明白了。。。。


template<class _Pr, class _Ty1, class _Ty2> inline
bool __CLRCALL_OR_CDECL _Debug_lt_pred(_Pr _Pred, const _Ty1& _Left, const _Ty2& _Right,
const wchar_t *_Where, unsigned int _Line)
{ // test if _Pred(_Left, _Right) and _Pred is strict weak ordering
if (!_Pred(_Left, _Right))
return (false);
else if (_Pred(_Right, _Left))
_DEBUG_ERROR2("invalid operator<", _Where, _Line);
return (true);
}

跟踪了stl的源代码 ,终于想通了。(不知对不对?)
如果按照顺序插入的话,将来就无法查找了(查找是根据键值比较的),所以这个库在插入的时候就进行了判断,判断如果 用compare左右判断 和右左判断都是
正确的话,直接断言失败!
hai040 2009-02-17
  • 打赏
  • 举报
回复
<
应该要符合一个条件
a<b和b<a不能同时成立
InfidelX 2009-02-17
  • 打赏
  • 举报
回复
楼主逻辑上面有问题,漏掉了比较语句。
InfidelX 2009-02-17
  • 打赏
  • 举报
回复
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <set>
using namespace std;

class compareInt
{
public:
bool operator()(const int &a,const int &b)
{
//没有比较,无论怎么都返回1,肯定错误,这里给出比较规则啊。
return a>b?1:0;
}
};

int main()
{
set<int,compareInt> st1;
st1.insert(1);
st1.insert(-1);
copy(st1.begin(),st1.end(),ostream_iterator<int>(cout," "));
system("pause");
return 0;
}
FanTasyCC 2009-02-17
  • 打赏
  • 举报
回复
改成:
class compareInt
{
public:
bool operator()(const int &a,const int &b) const
{
return 1;//如果是return a<b,就正确了,但这么写为啥不对。
}
};
sagegz 2009-02-17
  • 打赏
  • 举报
回复
运行下的确有问题
sagegz 2009-02-17
  • 打赏
  • 举报
回复
我用的也是VS2005


//#include "stdafx.h"
#include <assert.h>
#include <set>
using namespace std;

class compareInt
{
public:
bool operator()(const int &a,const int &b)
{
return 1;//如果是return a<b,就正确了,但这么写为啥不对。
}
};

int main()
{
set<int,compareInt> st1;
st1.insert(1);
st1.insert(-1);
return 0;
}
lijinfenghust 2009-02-17
  • 打赏
  • 举报
回复
vs2005 开发环境
lijinfenghust 2009-02-17
  • 打赏
  • 举报
回复
执行一下看看
到第二个inset的时候就弹断言了
sagegz 2009-02-17
  • 打赏
  • 举报
回复
我这没问题.

65,211

社区成员

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

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