【问题标题】:error: no matching function for call to 'swap'错误:没有匹配的函数调用“交换”
【发布时间】:2018-09-18 06:15:17
【问题描述】:

我正在尝试按 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: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',但不是同一个问题。

【问题讨论】:

标签: algorithm sorting c++11 quicksort swap


【解决方案1】:

sort算法中swap函数使用的数据类型必须是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)
    {}
};

【讨论】:

  • 所以说到底还是跟可能的重复关系密切。
猜你喜欢
  • 2015-04-29
  • 2013-05-05
  • 2012-12-28
  • 2015-03-31
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
相关资源
最近更新 更多