【问题标题】:Cant insert to std::map (G++)无法插入到 std::map (G++)
【发布时间】:2013-04-07 22:48:00
【问题描述】:

我有以下问题:

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++ 中修复此错误,在 Windows 上一切正常

谢谢!

【问题讨论】:

  • 重新安装 GNU Compiler Collection!!!!!!!!!!!!1
  • 您确定在 Windows 上一切正常吗?尝试编译实际调用 test() 函数的代码,我想你也会发现 VC++ 发出的错误。 @AndyProwl 的回答很到位。

标签: c++ g++ stdmap


【解决方案1】:

如果您希望能够在std::set 中使用它,您必须为您的ServerPP 数据结构定义operator &lt;。例如:

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,显示代码正在编译。

【讨论】:

  • 你能在另一个网站上重新上传你的例子吗?当前不显示任何内容。
猜你喜欢
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 2010-09-10
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多