2013-04-07 49 views
3

我有以下煩惱:廣東話插入到std ::地圖(G ++)

struct ServerPP { 
    std::string name; 
    int id; 
    int expires; 
}; 
std::map<std::string, std::set<ServerPP>> RemindTable; 

int test(std::string email, ServerPP serv) 
{ 
    RemindTable[email].insert(serv); // error when compile in this row below 
} 

錯誤G ++:

In file included from /usr/include/c++/4.4/string:50, 
       from /usr/include/c++/4.4/bits/locale_classes.h:42, 
       from /usr/include/c++/4.4/bits/ios_base.h:43, 
       from /usr/include/c++/4.4/ios:43, 
       from /usr/include/c++/4.4/istream:40, 
       from /usr/include/c++/4.4/sstream:39, 
       from stdafx.h:19, 
       from ActiveReminder.cpp:4: 
/usr/include/c++/4.4/bits/stl_function.h: In member function 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = ServerPP]': 
/usr/include/c++/4.4/bits/stl_tree.h:1170: instantiated from 'std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = ServerPP, _Val = ServerPP, _KeyOfValue = std::_Identity<ServerPP>, _Compare = std::less<ServerPP>, _Alloc = std::allocator<ServerPP>]' 
/usr/include/c++/4.4/bits/stl_set.h:411: instantiated from 'std::pair<typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(const _Key&) [with _Key = ServerPP, _Compare = std::less<ServerPP>, _Alloc = std::allocator<ServerPP>]' 
ActiveReminder.cpp:32: instantiated from here 
/usr/include/c++/4.4/bits/stl_function.h:230: error: no match for 'operator<' in '__x < __y' 

如何解決在G ++這個錯誤,就一切ok窗口

謝謝!

+0

重新安裝GNU編譯器集合!!!!!!!!!!!! 1 – 2013-04-07 22:49:49

+2

你確定在Windows上一切正常嗎?嘗試編譯實際調用'test()'函數的代碼,我想你也會發現VC++發出的錯誤。 @ AndyProwl的答案是現貨。 – 2013-04-07 22:54:00

回答

10

如果您想要在std::set中使用它,則必須爲您的ServerPP數據結構定義operator <。例如:

bool operator < (ServerPP const& lhs, ServerPP const& rhs) 
{ 
    return (lhs.id < rhs.id); 
} 

或者,您也可以定義自己的比較,並std::set提供的類型作爲第二個模板參數:

struct serv_comp 
{ 
    bool operator() (ServerPP const& lhs, ServerPP const& rhs) 
    { 
     return (lhs.id < rhs.id); 
    } 
}; 

std::map<std::string, std::set<ServerPP, serv_comp>> RemindTable; 

下面是該代碼編譯一個live example

+0

你能否在其他網站上重新上傳你的實例?目前沒有顯示任何東西。 – gon1332 2015-09-10 12:33:43

+0

@ gon1332:完成,謝謝。 – 2015-09-10 12:36:59