binary_search 通过其成员函数的 return 变量找到一个 class 对象 [c++]
binary_search to find a class object by the return variable of its member function [c++]
我有一个 class 对象的向量,按其整数索引排序。但是对象的索引是由 class 的成员函数生成的 - 所以没有 int id
作为成员变量存储。
class boundary
{
public:
int get_id();
}
std::vector<boundary> sample;
现在我需要找到 boundary
对象,它是由 get_id()
生成的 int id
与我正在搜索的 int value
相同。
auto &iter = binary_search(sample.begin(),sample.end(), 5, custom_function)
//should compare iter.get_id() == 5
在这种情况下可以使用binary_search吗?我该如何实现?
在这种情况下您应该使用 std::lower_bound:
bool custom_function(boundary& obj, int id) { return obj.get_id() < id; }
...
auto iter = lower_bound(sample.begin(),sample.end(), 5, custom_function);
(如果你想要更好的性能,用函数对象替换函数指针)
您可以创建一个满足"Compare"概念的对象。
http://en.cppreference.com/w/cpp/concept/Compare
例如:
class Compare {
public:
bool operator()(boundry a, boundry b) {
return a.get_id() < b.get_id();
}
}
假设:您想要获得对所查找元素的 引用(而不是它的迭代器)。
boundary& find_boundary(std::vector<boundary>& sample, int id)
// precondition: a boundary with id does exist in the sample
{
auto less_by_id = [](boundary const& b, int id) // lambda is faster than function pointers
{ return b.get_id() < id; };
auto it = lower_bound(sample.begin(), sample.end(), id, less_by_id);
assert (it != sample.end());
assert (it->get_id() == id);
return *it;
}
现在,您可以使用它了:
boundary& b = find_boundary(sample, 5);
我有一个 class 对象的向量,按其整数索引排序。但是对象的索引是由 class 的成员函数生成的 - 所以没有 int id
作为成员变量存储。
class boundary
{
public:
int get_id();
}
std::vector<boundary> sample;
现在我需要找到 boundary
对象,它是由 get_id()
生成的 int id
与我正在搜索的 int value
相同。
auto &iter = binary_search(sample.begin(),sample.end(), 5, custom_function)
//should compare iter.get_id() == 5
在这种情况下可以使用binary_search吗?我该如何实现?
在这种情况下您应该使用 std::lower_bound:
bool custom_function(boundary& obj, int id) { return obj.get_id() < id; }
...
auto iter = lower_bound(sample.begin(),sample.end(), 5, custom_function);
(如果你想要更好的性能,用函数对象替换函数指针)
您可以创建一个满足"Compare"概念的对象。 http://en.cppreference.com/w/cpp/concept/Compare
例如:
class Compare {
public:
bool operator()(boundry a, boundry b) {
return a.get_id() < b.get_id();
}
}
假设:您想要获得对所查找元素的 引用(而不是它的迭代器)。
boundary& find_boundary(std::vector<boundary>& sample, int id)
// precondition: a boundary with id does exist in the sample
{
auto less_by_id = [](boundary const& b, int id) // lambda is faster than function pointers
{ return b.get_id() < id; };
auto it = lower_bound(sample.begin(), sample.end(), id, less_by_id);
assert (it != sample.end());
assert (it->get_id() == id);
return *it;
}
现在,您可以使用它了:
boundary& b = find_boundary(sample, 5);