我有一个类myClass
,它使用一些双值beta
操作,这些值作为类成员存储在它的成员函数g
中。 它对它们进行排序,并将排列存储在类成员std::vector
:
double MyClass::g() {
// ...
sorted_beta_ind.resize(n);
for(unsigned int i=0; i<n; ++i) {
sorted_beta_ind[i] = i;
}
std::sort(sorted_beta_ind.begin(), sorted_beta_ind.end(),
[this] (const int &a, const int &b) {++op_cmp; return beta[a] > beta[b];});
// ...
}
接下来,我希望在另一个成员函数f
中有几个有序的索引集,它将以与sorted_beta_ind
中相同的顺序存储索引。 我试图使用std::set
对象,因此,我需要一个比较器。 我想出的最好的解决方案是lambda函数
double MyClass::f() {
auto ind_comp = [&order = sorted_beta_ind] (const int &a, const int &b) {
int pos_a = ~0, pos_b = ~0;
for(unsigned int i=0; i<order.size(); ++i) {
if(order[i] == a) {
pos_a = i;
}
if(order[i] == b) {
pos_b = i;
}
}
return pos_a < pos_b;
};
std::set<int, decltype(ind_comp)> d0, d1;
// the rest of the function which uses std::union and std::instersection
}
但在建设这个项目时我得到了
error: use of deleted function ‘MyClass::f()::<lambda(const int&, const int&)>& MyClass::f(int**, int)::<lambda(const int&, const int&)>::operator=(const MyClass::f()::<lambda(const int&, const int&)>&)’
这个方法能行得通吗?还是我应该尝试其他的方法?
捕获lambda表达式,就像您的一样,是不可默认构造的。 这正是std::set
试图做的事情,除非它接收到一个可以作为构造函数调用参数复制的比较器对象。 即:
std::set<int, decltype(ind_comp)> d0, d1;
在这里,std::set
只知道比较器的类型,并将尝试使用其默认构造函数构建比较器。 取而代之的是:
std::set<int, decltype(ind_comp)> d0(ind_comp), d1(ind_comp);
// ~~~~~~~^ ~~~~~~~^