【发布时间】:2018-04-02 07:17:44
【问题描述】:
我正在尝试将 shared_ptrs 的向量排序为 Food 对象。 食品类定义为:
class Food {
private:
// Human-readable description of the food, e.g. "all-purpose wheat
// flour". Must be non-empty.
std::string _description;
// Human-readable description of the amount of the food in one
// sample, e.g. "1 cup". Must be non-empty.
std::string _amount;
// Number of grams in one sample; must be non-negative.
int _amount_g;
// Energy, in units of kilocalories (commonly called "calories"), in
// one sample; must be non-negative.
int _kcal;
// Number of grams of protein in one sample; most be non-negative.
int _protein_g;
public:
Food(const std::string& description,
const std::string& amount,
int amount_g,
int kcal,
int protein_g)
: _description(description),
_amount(amount),
_amount_g(amount_g),
_kcal(kcal),
_protein_g(protein_g) {
assert(!description.empty());
assert(!amount.empty());
assert(amount_g >= 0);
assert(kcal >= 0);
assert(protein_g >= 0);
}
const std::string& description() const { return _description; }
const std::string& amount() const { return _amount; }
int amount_g() const { return _amount_g; }
int kcal() const { return _kcal; }
int protein_g() const { return _protein_g; }
};
使用
// Alias for a vector of shared pointers to Food objects.
using FoodVector = std::vector<std::shared_ptr<Food>>;
我的排序算法是:
std::unique_ptr<FoodVector> greedy_max_protein(const FoodVector& foods,
int total_kcal)
{
std::unique_ptr<FoodVector> result(new FoodVector);
int result_cal = 0;
sort(foods.begin(), foods.end(), sortByProtein); //sorting error
...
这里的排序函数发生错误^^,我的sortByProtein函数是:
bool sortByProtein(const std::shared_ptr<Food>&lhs, const std::shared_ptr<Food>&rhs)
{
return lhs->protein_g() > rhs->protein_g();
}
我不断得到二进制 '='no 运算符,它采用左操作数类型 'const std::shared_ptr' 或没有可接受的转换。我尝试创建自己的排序功能,但我得到了同样的错误。我需要在我的班级中重载 operator= 吗?如果是这样,我该怎么做?任何帮助将不胜感激!
编辑
通过创建新指针解决了这个问题:
FoodVector *sorted = new FoodVector(foods);
谢谢!
【问题讨论】:
-
const FoodVector& foods,- 如果foods是const,则不能排序(或以其他方式修改)。 -
那么,如果我从非 const 的 foods 向量创建一个新向量,那么我可以使用排序算法对其进行排序吗?
-
@DallasM,是的,或者只是删除
const修饰符 -
好的,我得到了它的工作谢谢你的帮助!
标签: c++ class sorting vector shared-ptr