error: no matching function for call to 'swap'

error: no matching function for call to 'swap'

我正在尝试根据权重的大小对 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;
}

这是错误的一部分:

exited with non-zero code (1).

In file included from solution.cc:1:

In file included from /usr/include/c++/v1/iostream:38:
In file included from /usr/include/c++/v1/ios:216:
In file included from /usr/include/c++/v1/__locale:15:
In file included from /usr/include/c++/v1/string:439:
/usr/include/c++/v1/algorithm:3856:17: error: no matching function for call to 'swap'

            swap(*__first, *__last);

            ^~~~

我试过这个解决方案 ,但这不是同一个问题。

swap函数在sort算法中使用的数据类型必须是MoveAssignable,然后可以进行如下操作

CakeType c1, c2;
c1 = move(c2); // <- move c2 to c1

但在您的情况下 CakeType 具有 const 数据成员。您只能在构造函数中为 const 数据成员赋值。无法编译代码,因为此限制无法生成默认 move/copy 赋值运算符(对 const 成员的赋值是非法的)。

从您的 class 定义中删除 const 说明符,代码将起作用。

class CakeType 
{
public:
    unsigned int weight_;
    unsigned int value_;

    CakeType(unsigned int weight = 0, unsigned int value = 0) :
        weight_(weight),
        value_(value)
    {}
};