Cant insert to std::map (G++)
Cant insert to 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上一切正常
谢谢!
如果您想在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;
下面是一个显示代码编译的实际示例。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 使用一个考虑到std::map中键值的滚动或换行的键
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 允许从 std::map 的密钥窃取资源?
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 使用字符数组作为 Map 中的键
- C++如何创建 std::map
- C++ equivalent to Java Map getOrDefault?
- 从其他容器中移动构造"std::map"
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射