【问题标题】:How to sort array of objects from derived template class C++如何从派生模板类C++中对对象数组进行排序
【发布时间】:2016-09-05 06:38:54
【问题描述】:

这里我有来自类ColVol 的对象数组,它用int 定义了三维点-类型颜色和体积(int 也是)。如果颜色在 [1,10] 之间,任务是按体积对数组进行排序。错误是the expression must be modifiable lvalue?Here 只是函数的声明。我不知道什么类型的排序在这里最好,为什么当tempvariable 是int, object.get_method() (在这种情况下数组是f[] and f[i].get_volume()isint`时给我这个错误?它们是同一类型。

template<class T> class Point3 {
    T x, y, z;
public:
    Point3();
    void print() const;    
}; 
template<class T, class U> class ColPoint3 :public Point3<T> {
    U color;
public:
    ColPoint3();
    void print() const;
};
template<class T, class U, class V> class ColVol :public ColPoint3<T, U> {
    V volume;
public:
    ColVol();
    void print() const;
    V get_volume() {
        return volume;
    }
};    
int main() {
    const int n = 2;
     ColVol<double, int, int>  *f;
    f = new ColVol<double, int, int>[n];
    for (int i = 0; i < n; i++) {
        f[i];
    }
            int temp;
    for (int k = 0; k < n; k++) {
        if (f[k].get_color() >= 1 || f[k].get_color() <= 10) {
            for (int i = 0; i < n - 1; i++) 
                for (int j = 0; j < n - i + 1; j++) 
                    if (f[j].get_volume() > f[j + 1].get_volume()) {
                        temp = f[j].get_volume();
                        f[j].get_volume() = f[j+1].get_volume();
                        f[j + 1].get_volume() = temp;   

                    }
                 }
            }
}

【问题讨论】:

  • 对于带颜色的 3D 点,“体积”是什么意思?

标签: c++ arrays sorting templates


【解决方案1】:

您需要以下修复(至少可以编译):

将方法 get_color 添加到 ColPoint3:

U get_color(){
    return color;
}

更改 get_volume 的签名:

V& get_volume() {
 ^~~~!
    return volume;
}

最后定义你的构造函数

[编辑]

至于排序,为什么不 std::sort 呢?

std::sort(f, f + n, [](auto &lop, auto  &rop){
    return lop.get_volume() < rop.get_volume();
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-22
    • 2021-02-18
    • 2012-08-27
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多