c++ - 将自定义谓词重新表述为标准谓词

标签 c++

我正在处理的一个程序包含这个谓词结构:

struct Unlike {
    Unlike(const Vertex& in) : a(in) {}
    bool operator()(const Vertex& b) {
        return !(a==b);
    }
    const Vertex& a;
};

顶点是具有(在其他成员中)具有成员 X、Y、Z 的结构坐标的结构。使用这些函数进行比较:

bool operator==(const Vertex& a, const Vertex& b) {
    bool res =  a.coord.X == b.coord.X &&
        a.coord.Y == b.coord.Y &&
        a.coord.Z == b.coord.Z;
    return res;
}
inline bool operator!=(const Vertex& a, const Vertex& b) {
    bool res = !(a==b);
    return res;
}

它是这样使用的:

std::vector<Vertex> vertices;
// Fill and sort vertices
std::vector<Vertex>::iterator vcur, vnext;
vcur = vertices.begin();
while(vcur != vertices.end()) {
    vnext = std::find_if(vcur, vertices.end(), Unlike(*vcur));
    // Loop over [vcur, vnext]
    vcur = vnext;
}

因此我们对比较相等的所有顶点执行一些计算。

我正在清理代码,希望摆脱 Unlike 结构。我试着这样做,在我看来,这样做的意图更清晰:

vnext = std::adjacent_find(vcur, vertices.end(), std::not_equal_to<Vertex>());

但这并没有保留相同的行为,而是进入了无限循环。为什么?我是否误解了 adjacent_findnot_equal_to

最佳答案

std::adjacent_find 向前查找一项 并在谓词为真时返回迭代器。

(1) 例如,如果您对两个字母的列表使用 not_equal_to ['a','b'] 并且您当前的迭代器指向 'a' 然后谓词 将为正,因为 'a' 不等于 next 'b' 和 std::adjacent_find 返回一个迭代器,它是对“a”的引用。

(2) 在您的第一个版本中,find_if 首先迭代到“b”,然后才将“b”与 'A'。结果我们有一个迭代器,它是对“b”的引用。

关于c++ - 将自定义谓词重新表述为标准谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6707701/

相关文章:

c++ - SSE、内在函数和对齐

c++ - 第一次出现的非重复数字

c++ - 将 native C++ 类公开给 VB.NET

c++ - OpenGL:点在无穷远的三角形

c++ - 我需要在Boost线程函数中调用unlock()吗?

c++ - 手动调用析构函数未被评估为引用变量

c++ - 如何在 Qt Quick 中将 QML 项转换为相应的 C++ 项

C++ - reference& operator= 在这里做什么

c++ - constexpr 函数和硬编码参数

c++ - 有没有办法阻止 clang-format 在返回后放置空间?