当结构体作为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; }