c++ - 重载运算符在使用 std::map 时产生错误

标签 c++ dictionary

class A
{
private:
    int a;
public:
    A( int set )
    {
        a = set;
    };
    ~A();
    bool operator <(const A& ref )
    {
        return this->a < ref.a;
    };
    bool operator ==(const A& ref )
    {
        return this->a == ref.a;
    };
};

int _tmain(int argc, _TCHAR* argv[])
{

    map<A,int>m;
    A a( 1 );
    m.insert( make_pair( a, 2 ) );
    for( map<A,int>::iterator it = m.begin(); it != m.end(); ++it )
    {

    }
    return 0;
}

生成 C2678:http://msdn.microsoft.com/en-us/library/ys0bw32s(v=vs.80).aspx

对于运营商<

如果我使用 m.find 也会为运算符生成 == 如何解决这个问题?

更具体地说,错误导致:

template<class _Ty>
    struct less
        : public binary_function<_Ty, _Ty, bool>
    {   // functor for operator<
    bool operator()(const _Ty& _Left, const _Ty& _Right) const
        {   // apply operator< to operands
        return (_Left < _Right);
        }
    };

功能性

最终案例:

struct MASTERPLAYER
{
    int a;
    bool operator==( const MASTERPLAYER& ref ) const 
    {
        return a == ref.a;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{

    MASTERPLAYER m;
    vector<MASTERPLAYER>v;
    v.push_back( m );
    std::find( v.begin(), v.end(), 2 );

最佳答案

您想将函数标记为 const,以表示它们不会修改调用它们的对象:

bool operator <(const A& ref ) const
{
    return a < ref.a;
};
bool operator ==(const A& ref ) const
{
    return a == ref.a;
};

关于c++ - 重载运算符在使用 std::map 时产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13428205/

相关文章:

c++ - 使用 DrawingSurfaceBackgroundGrid 重新绘制框架的正确技术是什么? (DirectX + xaml 应用程序)

c++ - 将数据容器传输到不同的类

Python - 通过键显示值的字典

oop - Map 和 SortedMap - 冗余方法声明

c++ - 允许 n 维坐标的有效方法?

c++ - 如何使用 range-v3 库迭代 C++ vector 并一次对两个值进行操作?

android - 如何从 .cpp 脚本启动 Android Activity ?

ios - swift : '(NSObject, AnyObject)' does not have a member named 'subscript'

swift - 如何将附近的位置设置到从 Firebase 检索的 TableView 中

javascript - 如何在javascript中创建列表字典