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