【发布时间】:2012-06-17 21:03:31
【问题描述】:
我有一个班级 cl1:
class c1
{
long double * coords;
...
}
我还有二班cl2:
class cl2
{
vector<cl1*> cl1_vec;
unsigned int d;
...
}
我想根据 coords[d] 对 cl2 中的 cl1_vec 进行排序,使用向量的排序函数。 所以我可以有类似的东西
sort(cl2_inst->cl1_vec.begin(),cl2_inst->cl1_vec.end(), ??? );
我尝试了类似的方法
sort the 'std::vector' containing classes
C++ std::sort with predicate function in Class
但我无法解决这个问题。
感谢您提供的任何帮助。
我试过的代码:
class cl1 {
public:
long double* coords;
cl1(long double *, unsigned int);
cl1();
cl1(const cl1& orig);
virtual ~cl1();
};
class cl2 {
public:
unsigned int d;
vector<cl1*> cl1_vec;
//the srting functions
static bool compareMyDataPredicate(cl1* lhs, cl1* rhs)
{
return (lhs->coords[d] < rhs->coords[d]);
};
// declare the functor nested within MyData.
struct compareMyDataFunctor : public binary_function<my_point*, my_point*, bool>
{
bool operator()( cl1* lhs, cl1* rhs)
{
return (lhs->coords[d] < rhs->coords[d]);
}
};
...
...
}
然后在主目录
std::sort(cl2_inst->cl1_vec.begin(),cl2_inst->cl1_vec.end(),cl2::compareMyDataPredicate() );
【问题讨论】:
-
请贴出您尝试过的代码,并说明哪些地方不起作用。
-
我将编辑问题并输入我尝试过的代码
-
您要排序什么?长双 * 坐标? cl1是什么类型?错字?
-
cl1 和 cl2 是在单独的 .hpp 和 .cpp 文件中定义的类。 cl2 中的 Dots(...) 用于未发布的构造函数和函数。
-
我认为我的问题在于我想使用的 d,它是一个 cl2 成员。 Coords 是一个长双精度数组。因此 cl1_vec 中的 cl1 实例应该使用 d 作为其坐标数组的索引进行排序。