Binary_search通过其成员函数的返回变量[C ]找到类对象
binary_search to find a class object by the return variable of its member function [c++]
我有一个由整数索引排序的类对象的向量。但是对象的索引是由类的成员函数生成的 - 因此,没有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);
(如果需要更好的性能,将功能指针替换为功能对象)
假设:您想向寻求的元素获得参考(而不是迭代器)。
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);
您可以创建满足"比较"概念的对象。http://en.cppreference.com/w/cpp/concept/compare
例如:
class Compare {
public:
bool operator()(boundry a, boundry b) {
return a.get_id() < b.get_id();
}
}
相关文章:
- 你能重载对象变量名本身返回的内容吗
- 将包含C样式数组的对象初始化为成员变量(C++)
- 将地址分配给本地指针后,公共对象的变量将消失
- 为什么我们再次从结构对象创建结构变量?
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- 从变量对象指向基对象
- C++ - 我可以创建编译时变量对象吗?
- 动态数组添加元素而不创建结构变量/对象
- Visual Studio C++ 编译器在局部变量对象上的奇怪行为
- 其中定义函数的静态局部变量对象
- QT良好的全局变量/对象处理
- r 值的匿名变量对象与真实对象
- QT 测试 - 变量/对象失去价值
- 访问私有变量对象
- C++访问具有相同名称的变量/对象的命名空间中的全局变量/对象
- C++-访问全局变量对象
- 表达式必须具有类类型:c++,将实例变量对象作为指针传递(点表示法参数)
- C++变量/对象和堆内存管理
- 如何在每次迭代中创建一个新变量/对象的循环
- 初始化现有变量/对象的新构造函数