首页 > 解决方案 > 如何根据已排序索引的向量对 std::set 索引进行排序?

问题描述

我有一个类MyClass,它使用一些双精度值进行操作beta,存储为类成员,在它的成员函数g中。它对它们进行排序并将排列存储在类成员中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];});
  // ...
}

接下来我想在另一个成员函数中有几个有序的索引集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&)>&)’

这种方法可以工作还是我应该尝试完全不同的东西?

标签: c++gccc++17gcc8

解决方案


像您一样捕获 lambda 表达式不是DefaultConstructible。这正是std::set试图做的事情,除非它接收到一个可以作为构造函数调用参数复制的比较器对象。那是:

std::set<int, decltype(ind_comp)> d0, d1;

这里std::set只知道比较器的类型,并将尝试使用其默认构造函数构造一个。相反,它应该是:

std::set<int, decltype(ind_comp)> d0(ind_comp), d1(ind_comp);
//                                   ~~~~~~~^      ~~~~~~~^

推荐阅读