我想创建一个 boost::binomial_heap
和一个使用外部数据的比较器,比如
bool compare(int a1, int a2)
{
return price[a1] < price[a2];
}
(例如,这里的 price
是 double 的 vector
。)
如何声明捕获价格
的比较函数?
最佳答案
以下 C++11 代码显示了如何执行此操作:
#include <vector>
#include <map>
int main()
{
std::vector<double> price{0.3, 0.2, 0.1};
auto cmp = [&price](int i, int j){return price[i] < price[j];};
std::map<int, float, decltype(cmp)> m(cmp);
m[2] = 'b';
m[1] = 'c';
}
线
std::vector<double> price{0.3, 0.2, 0.1};
定义 vector 价格
。
线
auto cmp = [&price](int i, int j){return price[i] < price[j];};
创建一个通过引用捕获 price
的 lambda 函数。
线
std::map<int, float, decltype(cmp)> m(cmp);
创建一个由该类型参数化的容器(在本例中为 std::map
),并将对象作为比较器。将其与不同的容器一起使用将是相似的。
关于c++ - 带捕获的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36240232/