C++ 排序类,内部包含类向量

c++ sort class with class vector inside

本文关键字:包含类 向量 内部 排序 C++      更新时间:2023-10-16

我有一个类cl1:

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

我还有一个二等 cl2:

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

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

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

我尝试了这样的应用

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

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

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

  • 为该结构提供一个构造函数,该构造函数unsigned int参数并将成员设置为该值。
  • 创建一个 compareMyDataFunctor 类型的对象,并将 d 的值传递给构造函数。
  • 使用此对象进行排序(std::sort 的第三个参数)

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

以下是基于您发布的代码的一些猜测:

静态函数和函子都使用成员d来决定对哪一列进行排序。但是d是一个实例变量,因此它不可用于任何静态变量。函子和静态成员函数都不知道要使用哪个可能的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 而不是 unsigned int 进行索引。std::vector也是如此
  • std::binary_function实例化中的类型与方法中的实际类型不匹配(可能是减少代码的问题)。
  • 不要使用using namespace std(我假设你从代码中的声明中这样做)。
  • 诸如此类的函子应将参数作为常量引用,而不是按值。

这就是我能想到的。下次尝试提供简短、独立、完整的示例时,人们就不必求助于猜测。