C ++ std :: sort on std :: vector <object> - 太多错误

时间:2015-07-12 23:30:13

标签: c++ sorting vector swap

我有两个班级[tabBarItem setSelectedImage:(UIImage*)image] TempFileYear正在获取温度为过去130年的.txt文件。构造函数读取此文件并将数据存储在TempFile中。现在我想添加一个排序函数,它以降序显示每年的平均温度。但是,当我使用std::vector<Year>来定义我的比较(struct中的第三个参数)时,我得到的错误太多了。我还试图重载std::sort - 运算符。也没用。

>

以下是错误消息的摘录:

class TempFile {
public:
    TempFile(std::string temp_file); // read from .txt file and push_back() the data into std::vector<Year> _years. 
    //The vector and constructor are working fine.

    int get_number_years() const;

    std::vector<Year> get_vector() const;
    void sort_descending() const;
private:
    std::vector<Year> _years;
    struct descending
    {
        bool operator() (const Year& y1, const Year& y2)
        {
            return (y1.get_average_temp() > y2.get_average_temp());
        }
    } temp_descending;
};

int TempFile::get_number_years() const
{
    return _years.size();
}

std::vector<Year> TempFile::get_vector() const
{
    return _years;
}

void TempFile::sort_descending() const
{
    std::sort(_years.begin(), _years.end(), temp_descending);
}


class Year {
public:
    Year(int year, float january, float february, ...);

    void print() const;

    float get_added_months() const;
    float get_average_temp() const;

    int get_year() const;

private:
    int _year;
    float _january, _february, ...; // all months

};

float Year::get_added_months() const
{
    return (_januar + _februar + _maerz + _april + _mai + _juni + _juli + _august + _september + _oktober
    + _november + _dezember);
}

float Year::get_average_temp() const
{
    return (get_added_months() / 12);
}

int Year::get_year() const
{
    return _jahreszahl;
}

1 个答案:

答案 0 :(得分:5)

TempFile::sort_descending()被标记为const,而您正试图通过_years修改std::sort成员。

从函数的签名中删除const说明符或使_years成为mutable将解决此问题。