1

我有一个类 cl1:

class c1
{
long double * coords;
...
}

我也有第二类 cl2:

class cl2
{
vector<cl1*> cl1_vec;
unsigned int d;
...
}

我想根据 coords[d] 对 cl2 中的 cl1_vec 进行排序,使用向量的 sort 函数。所以我可以有类似的东西

sort(cl2_inst->cl1_vec.begin(),cl2_inst->cl1_vec.end(), ??? );

我尝试了类似的方法

对包含类的“std::vector”进行排序

C++ std::sort 与 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() );
4

2 回答 2

1

d该错误是因为您正在从比较器函数的静态上下文访问非静态成员。使用第二种方法,方法如下:

  • 为该结构提供一个构造函数,该构造函数接受一个参数unsigned int并将一个成员设置为该值。
  • 创建一个 类型的对象compareMyDataFunctor,并将 的值传递d给构造函数。
  • 使用此对象进行排序(std::sort 的第三个参数)
于 2012-06-17T13:03:31.833 回答
0

我不确定这些问题,因为您对您的情况下“不起作用”的确切含义不够精确(不编译,编译但不排序等)。如果它没有编译(很可能是猜测),您没有发布错误消息,这也使得查找和解释问题变得非常困难。

以下是根据您发布的代码的一些猜测:

静态函数和仿函数都使用该成员d来决定对哪一列进行排序。然而d,它是一个实例变量,因此它不适用于任何静态的东西。仿函数和静态成员函数都不知道要使用哪个可能的 s,因为每个实例d都有一个。d

在不诉诸 C++11 特性 (lamdas) 的情况下做到这一点的最佳方法是为d您计划使用的仿函数提供一个构造函数。像这样的东西:

struct compareMyDataFunctor : public binary_function<cl1*, cl1*, bool>
{
    compareMyDataFunctor( unsigned int d ) : d( d ) {}
    bool operator()( cl1* lhs, cl1* rhs)
    {
        return (lhs->coords[d] < rhs->coords[d]);
    }

    unsigned int d;
};

这应该可以解决问题。

您发布的代码还有一些问题:

  • 数组应该使用类型size_t而不是 a来索引unsigned intstd::vectors也一样
  • 实例化中的std::binary_function类型与方法中的实际类型不匹配(可能是减少代码的问题)。
  • 不要使用using namespace std(我假设您从代码中的声明中使用)。
  • 诸如此类的函子应该将参数作为常量引用,而不是按值。

这就是我能想到的。下次尝试提出简短、独立、完整的例子,人们就不必去猜测了。

于 2012-06-17T13:01:48.343 回答