加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 一个结构中多点的运算符

发布时间:2020-12-16 09:59:30 所属栏目:百科 来源:网络整理
导读:我有一个存储两个应该可以互换的点的结构. struct Edge{ unsigned short firstIndex; unsigned short secondIndex; Edge(unsigned short firstIndex,unsigned short secondIndex) : firstIndex(firstIndex),secondIndex(secondIndex) {}}; operator ==方法应
我有一个存储两个应该可以互换的点的结构.

struct Edge
{
    unsigned short firstIndex;
    unsigned short secondIndex;
    Edge(unsigned short firstIndex,unsigned short secondIndex) :
        firstIndex(firstIndex),secondIndex(secondIndex) {}
};

operator ==方法应该如下(使它们可以互换)

bool operator == (const Edge& e2) const
{
    return 
        first == e2.first && second == e2.second || 
        first == e2.second && second == e2.first;
}

我期待创建一个运算符<和运算符>方法,以便在std :: map中使用struct

我尝试了以下(使用乘法)但它不起作用,因为在许多情况下,不同的边返回相同的值

bool operator < (const Edge& e2) const
{
    return first * second < e2.first * e2.second;
}

我想使用的代码如下:

std::map<Edge,unsigned int> edgePoints;
Edge e1(0,1);
Edge e2(1,2);
Edge e3(2,0);

edgePoints[e1] = 2;
edgePoints[e2] = 0;
edgePoints[e3] = 1;

虽然代码不适用于我的操作符<方法因为0 * 1 == 2 * 0所以当我调用edgePoints [e3]时,地图返回2 有没有人知道一个操作符<和运算符>我可以使用的方法,甚至是一些映射边缘的方法,以便使用std :: map

解决方法

我会以这种方式存储边的索引,小的索引总是第一个索引.看起来内部表示与您的应用程序无关.您不需要operator == for maps.这是示例结构:

struct Edge
{
    typedef unsigned short Idx; // prefer strong typedef cf boost
    Edge(Idx a,Idx b) 
    :
        firstIndex(std::min(a,b)),secondIndex(std::max(a,b))
    {}

    Idx firstIndex;
    Idx secondIndex;

    bool operator<(Edge const & other)
    {
        if (firstIndex != other.firstIndex) 
            return firstIndex < other.firstIndex;
        return secondIndex < other.secondIndex;
    }
}; // Edge

如果你想让你的实现更好,一些小的建议:

>首选std :: array< unsigned short,2>在单独的变量firstIndex和secondIndex上.这样做可以迭代索引.
>如果您正在使用数组,则可以缩短运算符<使用std::lexicographical_compare.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读