无法插入到 std::map (G++)

Cant insert to std::map (G++)(无法插入到 std::map (G++))

本文介绍了无法插入到 std::map (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++ 中修复此错误,在 Windows 上一切正常

How can i fix this error in G++, on windows all ok

谢谢!

推荐答案

你必须为你的 ServerPP 数据结构定义 operator < 如果你想能够在 std::set 中使用它.例如:

You have to define operator < for your ServerPP data structure if you want to be able to use it in std::set. For instance:

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

或者,您可以定义自己的比较器并将其类型作为第二个模板参数提供给 std::set:

Alternatively, you can define your own comparator and provide its type as the second template argument to 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;

这是一个显示代码编译的现场示例.

Here is a live example showing the code compiling.

这篇关于无法插入到 std::map (G++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无法插入到 std::map (G++)

基础教程推荐