如何仅使用一个键使用std :: binary_search? [英] How can I use std::binary_search using just a key?

查看:48
本文介绍了如何仅使用一个键使用std :: binary_search?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是,我发现"thingToSearchFor"对象的构造不佳.有没有更好的办法?与此类似吗?

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

推荐答案

执行:

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),因此只需直接输入值即可.

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

这篇关于如何仅使用一个键使用std :: binary_search?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆