我正在处理的一个程序包含这个谓词结构:
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_find
或 not_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/