How can I use std::binary_search using just a key?

不想你离开。 提交于 2019-12-21 17:07:05

问题


I have some data that is stored in a sorted vector. This vector is sorted by some key. I know the STL has an algorithm for checking if an element is in this sorted list. This means I can write something like this:

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

However I find the construction of the "thingToSearchFor" object inelegant. Is there a better way? Something similar to this?

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:


Do:

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

The predicate is called like pred(value, ...) or pred(..., value), so just take in the value directly.



来源:https://stackoverflow.com/questions/3474857/how-can-i-use-stdbinary-search-using-just-a-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!