我试图将自定义类型指定为std :: map的键.这是我用作键的类型.
struct Foo
{
Foo(std::string s) : foo_value(s){}
bool operator<(const Foo& foo1) { return foo_value < foo1.foo_value; }
bool operator>(const Foo& foo1) { return foo_value > foo1.foo_value; }
std::string foo_value;
};
Run Code Online (Sandbox Code Playgroud)
当与std :: map一起使用时,我收到以下错误.
error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Foo' (or there is no acceptable conversion) c:\program files\microsoft visual studio 8\vc\include\functional 143
Run Code Online (Sandbox Code Playgroud)
如果我改变下面的结构,一切都有效.
struct Foo
{
Foo(std::string s) : foo_value(s) {}
friend bool …Run Code Online (Sandbox Code Playgroud) 我需要创建一个映射,其中空间中的特定键位置映射到对象列表. std::map似乎是这样做的方式.
所以我在键入一个std::mapxyzVector
class Vector
{
float x,y,z
} ;
Run Code Online (Sandbox Code Playgroud)
,我正在做一个std::map<Vector, std::vector<Object*> >.所以请注意,这里的关键不是 a std::vector,它的对象class Vector只是我自己制作的数学xyz向量.
为了产生"严格弱的排序",我写了以下重载operator<:
bool Vector::operator<( const Vector & b ) const {
// z trumps, then y, then x
if( z < b.z )
{
return true ;
}
else if( z == b.z )
{
if( y < b.y )
{
// z == b.z and y < b.y …Run Code Online (Sandbox Code Playgroud)