说我有
std::set<classtype> set;
class classtype {
bool operator==(const classtype& ct) {
//..
}
};
//..
std::set<classtype>::iterator it = set.find(element);
查找是否使用类中的 == 运算符是否正确?
我的引用资料还说它有 log(n) 最坏情况运行时,其中 n 是集合中的元素数。这在内部是如何实现的?我知道关键是集合中的元素有一个顺序(因此插入需要很长时间才能创建该顺序),对于整数集来说,顺序的含义很清楚,但对于随机类来说则不是那么多。
最佳答案
来自 C++ 标准(23.2.4 关联容器)
3 The phrase “equivalence of keys” means the equivalence relation imposed by the comparison and not the operator== on keys. That is, two keys k1 and k2 are considered to be equivalent if for the comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false. For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.
成员函数find
根据比对对象求key comp
如果您没有明确指定比较对象,则该类默认使用标准功能对象 std::less
使用operator <
在其运算符(operator)功能内。所以你的类必须有运算符 < 定义。
如果你想使用operator ==
对于集合中的比较值,您可以使用标准算法 std::find
而不是方法 find
.
关于c++ - std::set<classtype>.find(element) 是否使用类中的 == 运算符来比较元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31035255/