Mic*_*son 5 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() );
}
Run Code Online (Sandbox Code Playgroud)
但是我发现"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() );
}
Run Code Online (Sandbox Code Playgroud)
GMa*_*ckG 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;
}
};
Run Code Online (Sandbox Code Playgroud)
谓词被称为pred(value, ...)或pred(..., value),所以直接接受该值.
| 归档时间: |
|
| 查看次数: |
1123 次 |
| 最近记录: |