如何只使用密钥来使用std :: binary_search?

时间:2010-08-13 07:42:47

标签: c++ stl binary-search

我有一些数据存储在有序矢量中。此向量按某个键排序。我知道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() );
}

但是我发现“thingToSearchFor”对象的构造不够优雅。有没有更好的办法?有类似的东西吗?

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 个答案:

答案 0 :(得分:11)

执行:

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;
    }
};

谓词的调用类似于pred(value, ...)pred(..., value),因此请直接接受该值。