c++ - std::set<classtype>.find(element) 是否使用类中的 == 运算符来比较元素?

标签 c++ time-complexity stdset

说我有

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/

相关文章:

将 std::string 作为函数参数传递时的 C++ 类型转换

c++ - 用 C++ (OpenCV) 读取像素值

c++ - 如何从 C++ 中的 set<int> 中删除所有偶数

c++ - c++结构中的可选变量(变量结构)

c++ - 为什么main函数不能返回负数?

python - Pandas DataFrame 搜索是线性时间还是常数时间?

algorithm - 条件变化时嵌套 while 的时间复杂度

performance - 对这些时间复杂度进行排序

c++ - std::set 带有自定义比较器的操作