【问题标题】:c++ sort class with class vector insidec++排序类,里面有类向量
【发布时间】: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 作为其坐标数组的索引进行排序。

标签: c++ class sorting vector


【解决方案1】:

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

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

【讨论】:

  • 我给了李考,因为他提供了代码。我希望我能标记两个答案。解决方法:我把LiKao的代码粘贴到cl2中,按照你说的做了。在 main 中创建 struct(cl2::struct) 的实例并将其用作第三个参数。说实话,我不是一个经验丰富的程序员,甚至从未听说过函子。谢谢你们。它奏效了。
【解决方案2】:

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

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

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

这就是我能想到的。下次试一下short, self contained, complete examples,就不用猜了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多