标准重载运算符<:设置(英语:SET)
Overloading Operator < for std::set
我有一个名为Dist的结构,
struct Dist {
Point firstPoint, secondPoint;
double value;
};
struct distCompare {
bool operator()(const Dist& x, const Dist& y) const {
return x.value < y.value;
}
};
并且我有一个集合来存储这个Object。
std::set<Dist, distCompare> distList;
如果x.firstPoint==y.firstPoint and x.secondPoint==y.secondPoint
,像x和y这样的两个Dist是相等的由于distCompare
比较两个Dist的值,我不能像这样使用set::find
:
for (auto q:input) {
Dist tempDist; tempDist.firstPoint = p; tempDist.secondPoint = q;
auto it = distList.find(tempDist);
if (it != distList.end()) { //'it' is always distList.end()
distList.erase(it);
}
}
我的Point类看起来是这样的:
class Point {
public:
Point(double a, double b){ x = a; y = b; }
Point(){}
double getX() const { return x; }
double getY() const { return y; }
void setX(double item){ x = item; }
void setY(double item){ y = item; }
private:
double x, y;
};
如何使运算符<以便我可以使用set::find
来找到相等的Dists?
std::set<T, Cmp>::find
进行二进制搜索,这取决于元素是有序的,并且总是使用Cmp
来决定等价性(这与等式不同),所以如果你不想让它基于distCompare
来查找。。。那么不要在集合中使用distCompare
!
由于distCompare
定义的排序与您对Dist
对象相等的定义完全无关,因此无法使用distCompare
排序执行快速二进制搜索,以查找被完全不同的函数认为相等的对象。根据相等的定义,可以有两个"相等"的元素,但根据distCompare
定义的顺序,它们在集合的两端排序。
您的选择是:
-
更改集合的比较函数,以便比较相等的项也可以使用比较函数比较相等项。
-
将集合替换为多索引容器,如Boost.MultiIndex.
-
通过设置的执行线性搜索
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- 为什么我无法更改"set<set>"循环中的值<int>
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- C ++设置与结构,set.find()函数使错误'invalid comparator'
- 系统( "bcdedit /set safeboot" ) 未将窗口设置为安全启动
- (Raspberry Pi 3)如何使用set()函数设置相机属性(来自raspicam/raspicam_cv.h)
- 是Set-user-id位设置
- Zooming Mandelbrot SET第二次设置不允许其放大所需的位置
- 标准重载运算符<:设置(英语:SET)
- C++ std::map<std::string, std::set<std::string>> .如何循环设置值?
- 在std::set中查找由自定义比较器设置的元素
- 将set选项设置为默认值