将自定义谓词重新表述为std-predicate

时间:2011-07-15 13:27:52

标签: 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

1 个答案:

答案 0 :(得分:1)

std :: adjacent_find 展望一个项目,如果谓词为真,则返回迭代器。

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

(2)在你的第一个版本中,find_if首先迭代到'b',然后才比较'b'     '一个'。结果我们有一个迭代器,它是对'b'的引用。

相关问题