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

c – 一个结构中多点的运算符,第1张

概述我有一个存储两个应该可以互换的点的结构. struct Edge{ unsigned short firstIndex; unsigned short secondIndex; Edge(unsigned short firstIndex, unsigned short secondIndex) : firstIndex(firstIndex), seco 我有一个存储两个应该可以互换的点的结构.

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.

总结

以上是内存溢出为你收集整理的c – 一个结构中多点的运算符全部内容,希望文章能够帮你解决c – 一个结构中多点的运算符所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1216919.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存