【问题标题】:How sort unique on a std::vector of Eigen::Vector?如何在 Eigen::Vector 的 std::vector 上排序唯一?
【发布时间】:2013-05-18 23:50:06
【问题描述】:

编译器无法确定该类型的小于运算符。我也尝试过使用 lambda 和谓词函数。

#include <Eigen/Dense>
typedef Eigen::Vector3f vec3;

inline bool operator<(const vec3 &lhs, const vec3 &rhs) {
    return lhs.x() < rhs.x() && lhs.y() < rhs.y() && lhs.z() < rhs.z();
}

inline bool cmpVecs(const vec3 &lhs, const vec3 &rhs) {
    return lhs.x() < rhs.x() && lhs.y() < rhs.y() && lhs.z() < rhs.z();
}


inline void removeDuplicates(std::vector<vec3> &con)
{
    std::sort(con.data(), con.data() + con.size());
    auto itr = std::unique(con.begin(), con.end(), cmpVecs);
    con.resize(itr - con.begin());
}

void init(std::vector<vec3> &verts) {
    removeDuplicates(verts);
}

VS 2012 错误:

algorithm(3618): error C2678: binary '”类型的左侧操作数 (或者没有可接受的转换) 1> with 1> [ 1> _Scalar=float, 1> _Rows=3, 1>
_Cols=1 1> ]

相关帖子:

【问题讨论】:

  • 您的比较函数不正确,因为std::sort 需要严格的弱排序谓词。 { if (lhs.x() &lt; rhs.x()) return true; if (rhs.x() &lt; lhs.x()) return false; if (lhs.y() &lt; rhs.y()) return true; if (rhs.y() &lt; lhs.y()) return false; return lhs.z() &lt; rhs.z(); }
  • 上面评论中的比较对我有用。这很难找到,尽管唯一性在 matlab 中很常见。

标签: c++ eigen


【解决方案1】:

std::sort 有一个可用的覆盖,允许您指定要使用的比较器,例如:

struct vec3comp{
    bool operator()(const vec3 &lhs, const vec3 &rhs){
        return lhs.x() < rhs.x() && lhs.y() < rhs.y() && lhs.z() < rhs.z();
    }
} mycomp;

std::sort(con.data(), con.data() + con.size(),mycomp);`

编辑:你能用 lambda 函数显示你的代码吗?它应该可以正常工作。

【讨论】:

  • TBH,我不认为我的排序方法不正确。我认为它是按浮点数而不是按 3 排序的。我只是复制了上面发布的链接。它也可能不是字节对齐的......现在检查一下。
  • 是的,static_assert 在测试 size == 3*sizeof(float) 时失败,这在某些方面是有道理的,尽管很糟糕。无论哪种方式,即使使用您链接的 struct 方法,它也会给我 operator
  • nvm 我在做 sizeof(sizeof())... 就像我说的。即使在尝试结构时仍然给我错误。
  • 原来我只是没有使用 std::sort() 的比较函数。我只是用独特的。我会投票,但我没有能力。
  • 只需标记答案即可。这样(已回答的)问题就不会保留在页面顶部。
猜你喜欢
  • 2019-07-08
  • 2013-06-06
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
相关资源
最近更新 更多