gpt4 book ai didi

c++ - binary_search 通过其成员函数的返回变量查找类对象 [c++]

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:18:54 25 4
gpt4 key购买 nike

我有一个按其整数索引排序的类对象 vector 。但是对象的索引是由类的成员函数生成的 - 因此没有 int id 存储为成员变量。

class boundary
{
public:
int get_id();
}

std::vector<boundary> sample;

现在我需要找到 boundary 对象,它是由 get_id() 生成的 int idint 值相同 我正在搜索。

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

(如果你想要更好的性能,用函数对象替换函数指针)

关于c++ - binary_search 通过其成员函数的返回变量查找类对象 [c++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42524433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com