gpt4 book ai didi

c++ - 如何根据已排序索引的 vector 对 std::set 索引进行排序?

转载 作者:行者123 更新时间:2023-12-01 14:47:36 26 4
gpt4 key购买 nike

我有一个类MyClass ,它使用一些 double 值 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&)>&)’

这种方法可以奏效,还是我应该尝试完全不同的方法?

最佳答案

像您一样捕获 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);
// ~~~~~~~^ ~~~~~~~^

关于c++ - 如何根据已排序索引的 vector 对 std::set 索引进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62389534/

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