I have a class MyClass
, which operates with some double values beta
, stored as a class member, in it's member function g
. It sorts them and stores the permutation in the class member std::vector<int> sorted_beta_ind
:
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];});
// ...
}
Next I want to have several ordered sets of indices in another member function f
, which will store the indices in the same order as in sorted_beta_ind
. I'm trying to use std::set
objects, and as such, I need a comparator. The best solution I figured out is a lambda function
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
}
but on building the project I get
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&)>&)’
Can this approach work or I should try something entirely else?
Capturing lambda expressions, like yours, are not DefaultConstructible. And that's exactly what std::set
tries to do unless it receives a comparator object that can be copied from as a constructor call argument. That is:
std::set<int, decltype(ind_comp)> d0, d1;
Here std::set
knows only the type of the comparator, and will attempt to constuct one using its default constructor. Instead, it should be:
std::set<int, decltype(ind_comp)> d0(ind_comp), d1(ind_comp);
// ~~~~~~~^ ~~~~~~~^