【问题标题】:C++ set keyCompare function for vectorC ++为向量设置keyCompare函数
【发布时间】:2015-07-23 12:32:25
【问题描述】:

我将 glm::ivec3 键存储在一组中。由于这种类型缺少 keyCompare 函数,因此我在结构中定义了它。如果我只有两个数字 a,b 我可以简单地写 a

我尝试了以下方法:

struct KeyCompare
{
    bool operator()(const glm::ivec3& a, const glm::ivec3& b)const
    {
        return a.x < b.x && a.y < b.y && a.z < b.z;
    }
};

typedef set<glm::ivec3, KeyCompare> ChunkSet;

现在我可以插入值了,但是在检查值是否存在时,它返回 true,而无需插入此键。

你知道向量的比较是如何进行的吗?

提前致谢!

【问题讨论】:

    标签: c++ vector set compare


    【解决方案1】:

    比较器必须实现strict weak ordering。你的没有。使用std::tie 的一种简单实现方法:

    #include <tuple>
    struct KeyCompare
    {
      bool operator()(const glm::ivec3& a, const glm::ivec3& b)const
      {
        return std::tie(a.x, a.y, a.z) < std::tie(b.x, b.y, b.z);
      }
    };
    

    这将执行 x、y 和 z 的字典比较。

    【讨论】:

    • 我喜欢一个可读性好的解决方案,站在一条线上并使用标准库。知道它如何将性能与具有多个 ifs 和 returns 的其他解决方案进行比较会很有趣
    【解决方案2】:

    你可以试试

    return a.x < b.x || (a.x == b.x && a.y < b.y) || (a.x == b.x && a.y == b.y && a.z < b.z);
    

    您的初始实现存在以下向量似乎相等的问题,因为 !(a &lt; b) &amp;&amp; !(b &lt; a) 为该实现保留:

    (3, 7, 12), (4, 6, 12)
    

    【讨论】:

    • 感谢您的解释!
    【解决方案3】:

    您需要一个比较函数,该函数在一组键 (ivec) 上定义 order。最常用的选择是所谓的lexicographic顺序(用于对字典中的单词进行排序),即先比较x坐标,然后比较y,然后比较z:

    struct KeyCompare {
        bool operator()(const glm::ivec3& a, const glm::ivec3& b)const
        {
            if(a.x < b.x) {
               return true;
            }
            if(a.x > b.x) {
              return false;
            }
            // Here, a.x = b.x, let's compare the y's
            if(a.y < b.y) {
               return true;
            }
            if(a.y > b.y) {
               return false;
            }
            // Here, a.x = b.x and a.y = b.y, let's compare the z's
            return (a.z < b.z);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-10
      • 2013-10-31
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多