zoukankan      html  css  js  c++  java
  • STL进阶--相等 vs 等价 (Equality vs Equivalence)

    相等性 vs 等价性

    问题: 以下两个find的结果分别指向什么?

    class Lsb_less {
       public:
       bool operator()(int x, int y) {
          return (x%10)<(y%10);
       }
    };
    
    set<int, Lsb_less> s = {21, 23, 26, 27};    //自定义比较方法
    
    
    set<int, Lsb_less>::iterator itr1, itr2;
    
    itr1 = find(s.begin(), s.end(), 36);  // 指向s.end() 
    
    itr2 = s.find(36);  // 指向26
    

    为什么不一样?

    set<int, Lsb_less> s = {21, 23, 26, 27};
    
    /*
     * 算法find()寻找相等性: if (x == y)  
     */
    
    itr1 = find(s.begin(), s.end(), 36);  // itr1指向s.end()
    
    
    /*
     * set<int>::find()寻找等效性: if ( !(x<y) && !(y<x) )
     */
    
    itr2 = s.find(36);  // itr2 points to 26
    

    总结

    • 如果函数使用<运算符或类似函数,它检查等效性。通常它是用于已排序数据的算法,或者已排序数据容器的成员函数,如关联容器。

    • 如果函数使用 == 运算符或类似函数,它检查相等性。通常不要求数据已排序。

    • 相等性的算法:

      search
      find_end
      find_first_of
      adjacent_search

    • 等效性的算法:

      binary_search // simple forms
      includes
      lower_bound
      upper_bound

    • 当使用某个函数搜索或者删除元素时,确保你理解了相等性和等效性之间的区别。

  • 相关阅读:
    决策树
    flask数据库的迁移
    flask的查询,一对多,多对多
    django的验证码
    第一讲:python环境配置(python2.7+python3.7)
    pytest
    【TS】-类型兼容性
    HTML--src和href的区别
    JS--为什么null是对象?
    JS--null和undefined的区别
  • 原文地址:https://www.cnblogs.com/logchen/p/10205429.html
Copyright © 2011-2022 走看看