簡體   English   中英

二進制表達式的無效操作數(常量點和常量點

[英]Invalid Operands to binary expression(const point and const point

    map<pair<int,int>,int>pairOfNumbers;
pairOfNumbers.insert(pair<pair<int,int>,int>({1,2},2));

這是有效的,但是

    map<pair<point,point>,int>PointsOnLine;
PointsOnLine.insert(pair<pair<point,point>,int>(make_pair(points[i],points[j]),count));

這沒有。

point 只是兩個整數 x 和 y 的結構; 我不斷收到錯誤'二進制表達式的無效操作數(常量點和常量點'這是點的結構。

    struct point
{
    int x;
    int y;
public:
    bool operator==(const point& p)
    {
        if(x==p.x && y==p.y)
            return true;
        else
            return false;
    }
    bool operator!=(const point& p)
    {
        if(x==p.x &&y==p.y)
            return false;
        else
            return true;
    }
};

如何在 map 中插入兩個點和它們之間的距離? 在 Xcode 我得到這個錯誤Xcode 中的錯誤信息

您的point類型不支持弱排序。 它沒有確定 is-less-than 的方法。 您可能認為您不需要它,因為您的point實際上隱藏在std::pair<point,point>但您確實需要。

std::pair<T1,T2>僅在T1T2支持時才支持弱排序。 在您的情況下,它們是相同的類型,因此對於std::pair<point,point>用作std::map<std::pair<point,pint>,T>中的鍵, point必須支持弱排序。

為了支持弱排序,您必須提供一個比較兩個有問題的對象的operator< ,或者提供一個執行相同操作的比較器仿函數類型。 您執行此操作的最簡單方法是:

#include <tuple>

struct point
{
    int x;
    int y;

    bool operator <(const point& p) const
    {
        return std::tie(x, y) < std::tie(p.x, p.y);
    }

    bool operator ==(const point& p) const
    {
        return !(*this < p || p < *this);
    }

    bool operator !=(const point& p) const
    {
        return *this < p || p < *this;
    }
};

我冒昧地重新定義了operator ==operator !=以利用正確的operator <的弱順序屬性。 這不是必需的,但最終如果操作員根植到盡可能基本的代碼會更容易。 通過上述更改,您應該能夠同時使用pointstd::pair<point,point>作為std::mapstd::set中的鍵類型。 實際上,嚴格的弱排序可以將所有基本比較器(<=、>、>=、、=、==)定義為operator <以一種或另一種形式(或相對於某種形式)的派生。 我挑戰你考慮它們,嘗試實現它們,最重要的是,編寫一些測試工具來驗證你的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM