5

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

1 回答 1

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

谓词称为 like pred(value, ...)or pred(..., value),因此只需直接取值即可。

于 2010-08-13T07:47:43.890 回答