代码之家  ›  专栏  ›  技术社区  ›  Michael Anderson

如何使用std::binary\u search只使用一个键?

  •  5
  • Michael Anderson  · 技术社区  · 15 年前

    我有一些存储在排序向量中的数据。这个向量是按某个键排序的。我知道STL有一个算法来检查元素是否在这个排序列表中。这意味着我可以这样写:

    struct MyData { int key; OtherData data; };
    struct MyComparator
    {
      bool operator()( const MyData & d1, const MyData & d2 ) const
      {
        return d1.key < d2.key;
      }
    };
    
    bool isKeyInVector( int key, const std::vector<MyData> &v )
    {
       MyData thingToSearchFor;
       thingToSearchFor.key = key;
       return std::binary_search( v.begin(), v.end(), thingToSearchFor, MyComparator() );
    }
    

    struct MyComparator2
    {
      bool operator()( const MyData & d1, const MyData & d2 ) const
      {
        return d1.key < d2.key;
      }
    };
    
    bool isKeyInVector2( int key, const std::vector<MyData> &v )
    {
       return std::binary_search( v.begin(), v.end(), key, MyComparator2() );
    }
    
    1 回复  |  直到 15 年前
        1
  •  11
  •   GManNickG    15 年前

    执行:

    struct MyComparator
    {
        bool operator()(int d1, const MyData & d2) const
        {
            return d1 < d2.key;
        }
    
        bool operator()(const MyData & d1, int d2) const
        {
            return d1.key < d2;
        }
    };
    

    谓词称为like pred(value, ...) pred(..., value)