首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何避免多变量结构“<”的实现

如何避免多变量结构“<”的实现
EN

Stack Overflow用户
提问于 2015-05-22 15:54:57
回答 4查看 72关注 0票数 1

类似于Preferred implementation of '<' for multi-variable structures,我为具有多个值的结构实现了一个小于操作符。我并不担心使用相等或小于运算符,让我们假设所有成员都正确地实现了这两者。我的结构有四个字段,操作符已经变得非常混乱:

代码语言:javascript
复制
struct Key {
    std::string s_name;
    bool b_mipmaps;
    bool b_clamp_to_edge;
    GLenum n_intformat;

    // [constructors here]

    bool operator <(const Key &other) const
    {
        return s_name < other.s_name || (s_name == other.s_name && (
            b_mipmaps < other.b_mipmaps || (b_mipmaps == other.b_mipmaps && (
            b_clamp_to_edge < other.b_clamp_to_edge || (b_clamp_to_edge == other.b_clamp_to_edge && (
            n_intformat < other.n_intformat))))));
        // compare two keys
    }
}

我想知道是否有一种常用的缩进样式,或者某种东西可以帮助您避免在括号中迷路,因为坦率地说,这是地狱,我认为这样的操作符中的bug会很微妙,很难跟踪/调试。是否有一种方法可以将其分解为一些原始函数?或者有一个STL函数可以做到这一点?

我目前正在使用C++03,但我对更新的标准持开放态度。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-05-22 16:07:43

您可以使用std::tie

代码语言:javascript
复制
bool operator <(const Key &other) const
{
    return std::tie(s_name, b_mipmaps, b_clamp_to_edge, n_intformat) <
        std::tie(other.s_name, other.b_mipmaps, other.b_clamp_to_edge, other.n_intformat);
}

别忘了#include <tuple>

票数 2
EN

Stack Overflow用户

发布于 2015-05-22 15:59:36

您可以使用几个if

代码语言:javascript
复制
bool operator <(const Key &other) const
{
    if (s_name != other.s_name) return s_name < other.s_name;
    if (!b_mipmaps && other.b_mipmaps) return true;
    if (b_mipmaps && !other.b_mipmaps) return false;
    if (!b_clamp_to_edge && other.b_clamp_to_edge) return true;
    if (b_clamp_to_edge && !other.b_clamp_to_edge) return false;
    return n_intformat < other.n_intformat;
    // compare two keys
}
票数 2
EN

Stack Overflow用户

发布于 2015-05-22 16:05:05

由于不知道代码中变量的类型,我发现使用变量名很难提出建议。

从您的代码中,不清楚操作符的语义应该是什么

(this->b_mipmaps && other.b_mipmaps)true

我使用以下模式:

代码语言:javascript
复制
bool operator <(const Key &other) const
{
   if ( this->member1 != other.member1 )
   {
      return (this->member1 < other.member1);
   }

   if ( this->member2 != other.member2 )
   {
      return (this->member2 < other.member2);
   }

   //
   // ...
   //

   return (this->memberN < other.memberN);
}

编辑

现在我知道b_mipmapsbool类型了,您可以使用:

代码语言:javascript
复制
   if ( this->b_mipmaps != other.b_mipmaps )
   {
      return (this->b_mipmaps < other.b_mipmaps);
   }

代码语言:javascript
复制
   if ( this->b_mipmaps != other.b_mipmaps )
   {
      return (!(this->b_mipmaps) && other.b_mipmaps);
   }

使用您发现更易读的样式。我觉得第一种形式更易读。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30401089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档