2011-07-15 44 views
1

一种程序,我正在包含此谓词结构:重新配制定制谓词如std-谓词

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; 
} 

所以我们进行一些calculati与这些功能的实现在所有比较相等的顶点上。

我正在做一些清理代码,并想摆脱Unlike结构。我试图做这样的,这在我看来是意图更加清晰:

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

,但没有保持相同的行为,而是进入一个无限循环。为什么?我误解了adjacent_find还是not_equal_to

回答

1

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

(1)例如,如果使用not_equal_to为两个字母 [“一”,“B”]和当前迭代器指向列表“一”,那么谓语 将是积极的,因为“一个”不等于下一个'b'和std :: adjacent_find 返回一个迭代器,它是对'a'的引用。 (2)在您的第一个版本中,find_if首先迭代到'b',然后只比较'b'和 'a'。因此,我们有一个迭代器,它是对'b'的引用。

+0

嗯,所以我想从'adjacent_find'增加迭代器?除了那最终会超过最后,所以它不是一种替代方案... – carlpett

+0

在任何情况下,std :: adjacent_find都不是你所需要的。 可能是这样的, vnext = std :: find_if(vcur,vertices.end(),bind2nd(not_equal_to (),* vcur)) – Mazurov

+0

好的,谢谢。你有推荐使用另一个'std :: find *'方法吗? – carlpett