【发布时间】:2017-05-09 23:22:27
【问题描述】:
我想创建一个输入事件对象到 std::functions 的映射。输入事件对象定义了 == 运算符,但由于 map 默认使用
#include <map>
struct Vertex
{
int x;
int y;
constexpr bool operator==(const Vertex& v)
{
return (x == v.x) && (y == v.y);
}
};
struct vertexCmp
{
bool operator()(const Vertex& v1, const Vertex& v2)
{
return v1 == v2;
}
};
int main()
{
std::map<Vertex, int, vertexCmp> _vertexMap;
Vertex v;
v.x = 1;
v.y = 1;
_vertexMap[v] = 1;
return 0;
}
但是,我收到以下编译器错误:
main.cpp||In member function ‘bool vertexCmp::operator()(const Vertex&, const Vertex&)’:|
main.cpp|21|error: passing ‘const Vertex’ as ‘this’ argument discards qualifiers [-fpermissive]|
main.cpp|11|note: in call to ‘constexpr bool Vertex::operator==(const Vertex&)’|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
我知道你不能在 const 对象上调用非 const 成员函数,但你会认为 constexpr 会满足这个要求,对吧?我觉得我在这里过度思考了我的方法,并且有更好的方法来构建它。
【问题讨论】:
-
constexpr和const是不同类型的“恒定性”。constexpr用于在编译时可能是常量的表达式。const不允许在运行时修改值。只需将const添加到您的operator== -
如果你不需要排序也没关系。
std::map需要排序才能正常工作。它不能通过平等比较来做到这一点。如果你做一个哈希函数,你可以使用std::unordered_map。 -
我实际上非常喜欢使用散列函数和 unordered_map 的想法,我认为这是一种更好的方法。谢谢。