我试图按照它们的重量大小对cakeTypes矢量进行排序。但是在排序实现中得到错误。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class CakeType
{
public:
const unsigned int weight_;
const unsigned int value_;
CakeType(unsigned int weight = 0, unsigned int value = 0) :
weight_(weight),
value_(value)
{}
};
bool compareCakes(const CakeType& cake1, const CakeType& cake2) {
return cake1.weight_ < cake2.weight_;
}
unsigned long long maxDuffelBagValue(const std::vector<CakeType>& cakeTypes,
unsigned int weightCapacity)
{
// calculate the maximum value that we can carry
unsigned cakeTypesSize = cakeTypes.size();
unsigned long long valueCalculator[weightCapacity+1][cakeTypesSize+1];
for (unsigned int i = 0; i<=weightCapacity+1; i++) {
valueCalculator[i][0] = 0;
}
for (unsigned int i = 0; i<=cakeTypesSize+1; i++) {
valueCalculator[0][i] = 0;
}
vector<CakeType> sortedCakeTypes(cakeTypes);
sort(sortedCakeTypes.begin(), sortedCakeTypes.end(), compareCakes);
return 0;
}
这是错误的一部分:
以非零代码退出(1)。
在solution.cc:1中包含的文件中:
在/ usr / include / c ++ / v1 / iostream中包含的文件中:38: 在/ usr / include / c ++ / v1 / ios:216中包含的文件中: 在/ usr / include / c ++ / v1 / __ locale中包含的文件中:15: 在/ usr / include / c ++ / v1 / string中包含的文件中:439: / usr / include / c ++ / v1 / algorithm:3856:17:错误:调用'swap'没有匹配函数
swap(*__first, *__last); ^~~~
我试过这个解决方案sort() - No matching function for call to 'swap',但它不是同一个问题。
在swap
算法中sort
函数使用的数据类型必须是MoveAssignable
,然后你可以执行如下操作
CakeType c1, c2;
c1 = move(c2); // <- move c2 to c1
但在你的情况下,CakeType
有const数据成员。您只能在构造函数中为const数据成员赋值。代码无法编译,因为此限制不能生成默认的移动/复制赋值运算符(赋予const成员是非法的)。
从类定义中删除const说明符,代码将起作用。
class CakeType
{
public:
unsigned int weight_;
unsigned int value_;
CakeType(unsigned int weight = 0, unsigned int value = 0) :
weight_(weight),
value_(value)
{}
};