相关疑难解决方法(0)

自定义类型作为地图的关键 - C++

我试图将自定义类型指定为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)

c++ operator-overloading stdmap

23
推荐指数
1
解决办法
2万
查看次数

在std :: map中使用(数学)向量

相关:我可以用什么std::map键作为键?

我需要创建一个映射,其中空间中的特定键位置映射到对象列表. 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)

c++ math operator-overloading stdmap

8
推荐指数
1
解决办法
1345
查看次数

标签 统计

c++ ×2

operator-overloading ×2

stdmap ×2

math ×1