如何对类成员向量进行排序
How to sort a class member vector?
我正在使用一个代码,该代码对每个元素都有一个键的列表进行排序,并且我正在使用STL函数sort。但是,我需要的关键函数必须是类的非静态函数,并且编译器拒绝接受该函数。任何建议都值得赞赏。
#include <bits/stdc++.h>
class Class {
public:
Class (int i): my_int(i) {}
int f (int x) { return x % my_int; }
bool key (int i1, int i2) { return f(i1) < f(i2); }
void sort_v () { std::sort(v.begin(), v.end(), this->key) }
private:
std::vector<int> v = {4,6,3,2};
int my_int;
};
int main() {
Class c(3);
c.sort_v();
return 0;
}
注意:友元函数不容易实现,因为key(int,int(的参数是自动传递的,并且由于f不是静态的,我们将无法传递"this"类数据。
只需使用 lambda:
void sort_v () {
std::sort(v.begin(), v.end(), [this](auto a, auto b) { return key(a, b); });
}
您可以使用
std::bind
:
void sort_v () {
using std::placeholders;
std::sort(v.begin(), v.end(), std::bind( &Class:key, this, _1, _2 ) );
}
或使用 lambda:
void sort_v () {
std::sort(v.begin(), v.end(), [this]( int x, int y ) { return key( x, y ); );
}
使您的方法有效。
相关文章:
- 计算排序向量的向量中唯一值的计数
- 查找两个排序向量中共有的元素
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 如何从C++的对的排序向量中获取有关给定值的相应对
- 对象接收堆栈溢出异常 c++ 的排序向量
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 指向指针排序向量的指针向量的 C++ 向量
- 未排序向量上的lower_bound/upper_bound
- 智能指针的排序向量:神秘崩溃
- 按类型排序向量并按类型或派生类型搜索
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- C++排序向量<double>与在<Object>双成员变量上键控的向量
- 字符串指针的排序向量
- 具有前导数字的字符串的排序向量
- 保证重新排序向量
- 结构解释的C 排序向量
- 更新排序向量的一个条目
- 通过在排序向量上使用二叉搜索来定位未排序向量中的元素
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- 使用QuickSort算法以降序排序向量