Sort () - There is no suitable function to call 'swap'

I just spent about an hour trying to figure out why I get 20 error messages like "Semantic issue - no matching function for call to 'swap'" when I try to build the next 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 people with the same problem seem to have made their algorithm a member of the class instead of a static member, but this is clearly not a problem.

+7
c ++ sorting xcode compiler-errors
source share
2 answers

Turns out this is a very simple problem, but not very obvious (and the error message doesn't help much in helping):

Remove the const declaration on run() - voilΓ‘.

+13
source share

The compiler refers to swap because std::sort internally uses the swap function. However, since the run member function is declared a constant function

 void run() const; 

then the object of the class itself is considered as a permanent object, and therefore the list of member members is also a permanent object

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

Therefore, the compiler tries to call swap with parameters that are permalinks or are not even links, and cannot find such a function.

+4
source share

All Articles