Search code examples
algorithmsortingc++11quicksortswap

error: no matching function for call to 'swap'


I am trying to sort cakeTypes vector by the size of their weight. But getting the error in sort implementation.

#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;
}

This is part of there error:

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);

            ^~~~

I tried this solution sort() - No matching function for call to 'swap', but it is not the same issue.


Solution

  • Data type which is used by swap function in sort algorithm must be MoveAssignable, then you can perform operation like below

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

    But in your case CakeType has const data members. You can assign values to const data members only in constructors. Code cannot be compiled because default move/copy assignment operator can't be generated by this restriction (assignment to const member is illegal).

    Remove const specifier from your class definition and code will work.

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