struct作为map的key时,需要重载该结构体

来源:互联网 发布:mysql删除sql语句 编辑:程序博客网 时间:2024/05/21 11:27

当结构体作为map中的key时,这个结构体必须重载"<"运算符,  否则将出错,看我完整代码:

 

#ifndef WIN32#include <string.h>#else#include <string>#endif#include <iostream>#include <map>using namespace std;typedef struct KeyNode_s{long key;bool operator < (const KeyNode_s& s) const{return key < s.key;}}KeyNode;typedef struct N_1{int c;}CRTPSession;typedef struct N_2{int d;}CJOpPlayback;typedef struct SessionInfo_s{CRTPSession*_session;CJOpPlayback*_opPlayback;SessionInfo_s(){_session = NULL;_opPlayback = NULL;}}SessionInfo;typedef struct Hello_s{char name[20];Hello_s(const char* s){strcpy(name, s);}bool operator < (const Hello_s& s) const{return strcmp(name, s.name) < 0;}}Hello;typedef std::pair<KeyNode, Hello> GBClientPair;typedef std::map<GBClientPair, SessionInfo> RtpSessionList;// map中的key是pair, 但是pair中有结构体, 所以这些结构体必须重载"<"运算符void test(){KeyNode knode;SessionInfo sinfo;Hello h("world");RtpSessionList list;GBClientPair pa(knode, h);list[pa] = sinfo;}int main(){test();return 0;}

1 0