比较两个用户定义的类型向量

时间:2018-03-07 11:40:06

标签: c++

我试图使用!=比较两个向量,但VS2015显示这些错误。

Error   C2672   'operator __surrogate_func': no matching overloaded function found  
Error   C2893   Failed to specialize function template 'unknown-type std::equal_to<void>::operator ()(_Ty1 &&,_Ty2 &&) const'

代码:

#include <vector>
struct Pixel 
{
    int m_nX;
    int m_nY;

    Pixel(int x, int y)
    {
        m_nX = x;
        m_nY = y;
    }
};

int main()
{
    std::vector<Pixel> vtrPixels1;
    vtrPixels1.emplace_back(1, 2);
    vtrPixels1.emplace_back(3, 4);

    std::vector<Pixel> vtrPixels2;
    vtrPixels2.emplace_back(2, 2);
    vtrPixels2.emplace_back(3, 4);

    if (vtrPixels1 != vtrPixels2)
        vtrPixels1 = vtrPixels2;

    return 0;
}

1 个答案:

答案 0 :(得分:4)

您需要为类==

重载运算符Pixel
struct Pixel
{
    int m_nX;
    int m_nY;

    Pixel(int x, int y)
    {
        m_nX = x;
        m_nY = y;
    }

    bool operator==(const Pixel& a) const{
        return a.m_nX == m_nX && a.m_nY == m_nY;
    }
};