Cant insert to 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++)
基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04