STL之map

来源:互联网 发布:中国有多少网络作家 编辑:程序博客网 时间:2024/06/12 22:04

一、使用自定义的对象作为key

以单向链表的节点为例进行说明,声明如下:

typedef struct Node{Node(int Data) : m_Data(Data), pNext(NULL) {}Node *pNext;int m_Data;}Node;
因为map容器是基于红黑树实现的,它会根据元素的key值进行排序,因此我们在创建map的时候需要指明key值之间进行比较所使用的仿函数,如果不显示指定,则默认使用less<>作为仿函数:

map<Node, Node> Nodes; //默认采用less<Node>作为仿函数map<Node, Node, greater<Node>> Nodes; //指定采用greater<Node>作为仿函数.

默认的less<>仿函数的源码如下:

template<class _Ty = void>struct less{// functor for operator<typedef _Ty first_argument_type;typedef _Ty second_argument_type;typedef bool result_type;constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const{// apply operator< to operandsreturn (_Left < _Right);}};
其中使用_Left < _Right进行元素之间的比较,所以我们自定义的类型Node必须要重载<操作符,类似地,如果指定greater<Node>作为仿函数,那么我们需要重载>操作符,以less<>为例:

bool operator < (const Node& other) const{return m_Data < other.m_Data;}
这样map容器就可以使用less<>仿函数对Node对象进行比较了,示例如下:

int main(){map<Node, Node> Nodes;Node* data[4];for (size_t i = 0; i < 4; i++){data[i] = new Node(i + 1);if (i)Nodes.insert(pair<Node, Node>(*data[i - 1], *data[i]));}//输出<1, 2> <2, 3> <3, 4> map<Node, Node>::iterator iter = Nodes.begin();while (iter != Nodes.end()){cout << "<" << iter->first.m_Data << ", " << iter->second.m_Data << ">" << endl;++iter;}return 0;}

二、使用自定义对象的指针作为key

如果使用自定义对象的指针作为key是否需要重载<或者>等操作符呢?其实不是必须的。因为指针之间本身就可以比较大小,如果不关心元素在容器内的排序,只关心<key, value>映射关系,则不需要实现仿函数或者重载<或者>等操作符.如果关系元素的顺序,则需要实现仿函数:

struct LessNode{// functor for operator<bool operator()(const Node* _Left, const Node* _Right) const{// apply operator< to operandsreturn (_Left->m_Data < _Right->m_Data);}};
示例如下:

//data[]是Node*数组.map<Node*, Node*, LessNode> MapNode;MapNode.insert(pair<Node*, Node*>(data[0], data[1]));MapNode.insert(pair<Node*, Node*>(data[1], data[2]));MapNode.insert(pair<Node*, Node*>(data[2], data[3]));//输出<1, 2> <2, 3> <3, 4> map<Node*, Node*, LessNode>::iterator it = MapNode.begin();while (it != MapNode.end()){cout << "<" << it->first->m_Data << " , " << it->second->m_Data << ">" << endl;++it;}
总结:不管key是自定义的对象还是对象的指针,红黑树中key值的比较是通过仿函数实现的,要么自己创建仿函数作为初始化参数,要么在自定义类型中重载相应的操作符以支持默认仿函数中元素的比较。




原创粉丝点击