读书人

关于使用struct做为地图关键字的有关问

发布时间: 2012-08-09 15:59:21 作者: rapoo

关于使用struct做为map关键字的问题
请看代码:
[code=C/C++]
typedef struct testStc
{
int a;
int b;
int c;
testStc()
{
a = 0;
b = 0;
c = 0;
}

bool operator < (const testStc& other) const
{
if( !(a < other.a) && !(other.a < a))
if( !(b < other.b) && !(other.b < b))
if( !(c < other.c) && !(other.c < c))
return false;
return true;
}
}StcKey;


int main()
{

std::map <StcKey,int> mapStcTest;

StcKey stcA,stcB,stcC,stcD;
stcA.a = 1;
stcA.b = 2;
stcA.c = 3;

stcB.a = 2;
stcB.b = 1;
stcB.c = 3;

stcC.a = 3;
stcC.b = 2;
stcC.c = 1;

stcD.a = 1;
stcD.b = 2;
stcD.c = 3;

mapStcTest.insert(make_pair(stcA,3));
mapStcTest.insert(make_pair(stcB,1));
mapStcTest.insert(make_pair(stcC,2));

std::map <StcKey,int> ::iterator iter = mapStcTest.find(stcD);
if(iter != mapStcTest.end())
{
printf( "1\n ");
}
}
[/code]


在插入第二个元素时,会断言,除第一个正常插入,后面的都会断言。这个地方有点不明白为什么。

[解决办法]
断言是什么??bool operator < (const testStc& other) 严格吗?通过<符号能否推导出=和>呢?
[解决办法]
逻辑错了,你这个是不等,不是小于

[解决办法]
map是用红黑树实现的,实际上是排了序的,你给这个判断是否相等的函数显然是错了,应该给<函数
[解决办法]
你去看一下map里面xtree的源码,operator < 不是你写的那样,函数原型就错了
[解决办法]
最好也把=也重载一下。

读书人网 >C++

热点推荐