set的比较函数问题为了去除重复点 想把点组给存到set中 要求一定的精度范围的点就认为相等C/C++ code具体
set的比较函数问题
为了去除重复点 想把点组给存到set中 要求一定的精度范围的点就认为相等
- C/C++ code
具体代码如下:int main(){ struct _ComparePt { bool operator()(const ZzGePoint3d& _Left, const ZzGePoint3d& _Right) const { if (FloatComp(_Left.x,_Right.x, 0.001) != 0) return (_Left.x < _Right.x); if (FloatComp(_Left.y,_Right.y, 0.001) != 0) return (_Left.y < _Right.y); return (FloatComp(_Left.z,_Right.z,0.001)==-1); } }; vector<ZzGePoint3d> ptArr; set<ZzGePoint3d, _ComparePt> ptSet(ptArr.begin(), ptArr.end()); vector<int> indexArr; indexArr.resize(ptArr.size()); for (int i = 0; i < ptArr.size(); ++i) { set<ZzGePoint3d, _ComparePt>::iterator it = ptSet.find(ptArr[i]); //这里得到的这个it可能等于ptSet.end() 应该是_ComparePt写的有问题 indexArr[i] = std::distance(ptSet.begin(), it); } return 0;}问题就是 这种写法是否可行 如果可以 给出正确的写法 否则把原因说一下。
[解决办法]
std::set 的比较函数要求 strict weak ordering,strict 表示 true == !comp(x,x)。不知道 FloatComp 返回值代表什么意义,不过我猜 _ComparePt(x,x) 返回 true,那么这样的函数对象不能作为 std::set 的比较函数。试一下这个吧。
- C/C++ code
bool operator () (ZzGePoint3d const& a, ZzGePoint3d const& b) const{ double const e = 0.001; if (a.x<b.x-e) { return 1; } if (a.x>b.x+e) { return 0; } if (a.y<b.y-e) { return 1; } if (a.y>b.y+e) { return 0; } if (a.z<b.z-e) { return 1; } if (a.z>b.z+e) { return 0; } return 0;}
[解决办法]
楼主,去找本《effective stl》认真啃啃吧。
你现在问的,和即将问的,都会直接找到答案的。 