java map的结构体_结构体作为map的key或放入set中,需要重载<运算符

结构体作为map的key或放入set中,需要重载

typedef struct tagRoadKey

{

int m_i32Type;

int m_i32Scale;

bool operator

{

if (m_i32Type != other.m_i32Type) // 类型按升序排序

{

return (m_i32Type < other.m_i32Type);

}

else // 如果类型相同,按比例尺升序排序

{

return (m_i32Scale < other.m_i32Scale);

}

}

} RoadKey;

也可以重载>运算符,示例如下:

#include

#include

#include

using namespace std;

class Array

{

private:

int m_i32Num1;

int m_i32Num2;

public:

Array(int i32Num1, int i32Num2);

bool operator >(const Array& other) const;

};

Array::Array(int i32Num1, int i32Num2)

{

m_i32Num1 = i32Num1;

m_i32Num2 = i32Num2;

}

bool Array::operator >(const Array& other) const

{

if (m_i32Num1 > other.m_i32Num1)

{

return true;

}

else

{

return false;

}

}

// 此结构体作为map的value

struct TInfo

{

int m_i32Num1;

int m_i32Num2;

};

int main(int argc, char* argv[])

{

map > stMap;

TInfo stInfo1 = { 1, 1};

stMap.insert(pair(Array(1, 2), stInfo1));

TInfo stInfo2 = { 2, 1, 1 };

stMap.insert(pair(Array(2, 2), stInfo2));

TInfo stInfo3 = { 3, 1, 1 };

stMap.insert(pair(Array(3, 2), stInfo3));

for (map >::iterator it = stMap.begin(); it != stMap.end(); ++it)

{

cout << it->second.m_i32Num1 << endl;

}

return 0;

}

说明:

map缺省是用less作为比较器,所以它要求作为Key的类要重载“”操作符就会报错。

反之,也可以显式地用greater作为比较器,此时就必要重载Key类中的“>”操作符了。

附:stl中map和set的声明,二者比较像,底层都是用红黑树实现的

template < class Key, class Compare = less,

class Allocator = allocator > class set;

template < class Key, class T, class Compare = less,

class Allocator = allocator > > class map;

template < class Key, class Compare = less,

class Allocator = allocator > class multiset;

template < class Key, class T, class Compare = less,

class Allocator = allocator > > class multimap;

从上面的声明可以看出,也可以定义一个函数对象Compare,声明map或set类型时传进入,如:

struct TTimeCompare

{

bool operator ()(const CTimerEvent* po1, const CTimerEvent* po2)const

{

return (po1->m_oNextTick < po2->m_oNextTick);

}

};

typedef multiset TEventSet;

struct ltstr // less than

{

bool operator()(const char* s1, const char* s2) const

{

return strcmp(s1, s2) < 0;

}

};

set stSet; // set

map stMap; // map

struct eqstr // equal

{

bool operator()(const char* s1, const char* s2) const

{

return strcmp(s1, s2) == 0;

}

};

hash_map, eqstr> stHashMap;  // hash_map

// 自定义hash函数

namespace std

{

template<>

struct hash

{

size_t operator()(const KEY_TYPE& key) const

{

//return key.Hash();

}

};

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值