Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort() - No matching function for call to 'swap'

Just spent about an hour trying to figure out why I would get 20 error messages of the type "Semantic issue - no matching function for call to 'swap'" when I try to build the following class (in XCode).

test.h

#include <iostream>
#include <string>
#include <vector>


class Test{
    std::vector<std::string> list;

    void run() const;
    static bool algo(const std::string &str1, const std::string &str2);
};

test.cpp

#include "test.h"


void Test::run() const {
    std::sort( list.begin(), list.end(), algo );
}


bool Test::algo(const std::string &str1, const std::string &str2){
    // Compare and return bool
}

Most of the people with the same problem seem to have made their algorithm a class member instead of a static member, but that is clearly not the problem here.

like image 478
Magnus Avatar asked Feb 27 '15 09:02

Magnus


2 Answers

It turns out it's a very simple problem, but not very obvious to spot (and the error message doesn't do a very good job in helping out either):

Remove the const declaration on run() - voilá.

like image 171
Magnus Avatar answered Nov 08 '22 18:11

Magnus


The compiler refers to swap because std::sort internally uses function swap. However as member function run is declared as constant function

void run() const;

then the object of the class itself is considered as a constant object and hence data member list also is a constant object

std::vector<std::string> list;

So the compiler tries to call swap with parameters that are constant references or even are not references and can not find such a function.

like image 31
Vlad from Moscow Avatar answered Nov 08 '22 17:11

Vlad from Moscow